交叉類型是將多個類型合並為一個類型。 這讓我們可以把現有的多種類型疊加到一起成為一種類型,它包含了所需的所有類型的特性。
示例
interface Person {
name: string
age: number
}
interface Student {
school: string
}
// ✅正確
const stu: Person & Student = {
name: 'Tom',
age: 23,
school: 'Oxford',
}
// ❌錯誤
// Property 'school' is missing in type ...
const stu: Person & Student = {
name: 'Tom',
age: 23,
}
// ❌錯誤
// Type '{ school: string; }' is missing the following properties from type 'Person': name, age
const stu: Person & Student = {
school: 'Oxford'
}
Person & Student
可以使用類型別名
interface Person {
name: string
age: number
}
interface Student {
school: string
}
type StudentInfo = Person & Student
// ✅正確
const stu: StudentInfo = {
name: 'Tom',
age: 23,
school: 'Oxford',
}
// ❌錯誤
// Property 'school' is missing in type ...
const stu: StudentInfo = {
name: 'Tom',
age: 23,
}
// ❌錯誤
// Type '{ school: string; }' is missing the following properties from type 'Person': name, age
const stu: StudentInfo = {
school: 'Oxford'
}
或者
interface Person {
name: string
age: number
}
type UserInfo = Person & {isAdmin: boolean, level?: string}
// ✅正確
const user1: UserInfo = {
name: 'Tom',
age: 23,
isAdmin: true,
level: 'A1',
}
// ❌錯誤
// Property 'isAdmin' is missing in type ...
const user2: UserInfo = {
name: 'Tom',
age: 23,
}