TypeScript--交叉類型


交叉類型是將多個類型合並為一個類型。 這讓我們可以把現有的多種類型疊加到一起成為一種類型,它包含了所需的所有類型的特性。

示例

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,
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM