這是我的問題的最小示例
interface Dog {
legs: number;
}
interface Person {
arms: number;
}
type Living = Person | Dog;
interface Speaker<T extends Living> {
speak: (living: T) => void;
};
const michel: Speaker<Person> = { speak: (person) => console.log(`I have ${person.arms} arms`) };
const speakers: Array<Speaker<Living>> = [michel];
它拋出這個錯誤
Type 'Speaker<Person>' is not assignable to type 'Speaker<Living>'.
Type 'Living' is not assignable to type 'Person'.
Property 'harms' is missing in type 'Dog' but required in type 'Person'
我想要一個Speaker接受任何型別的Living.
謝謝你的時間!
uj5u.com熱心網友回復:
按照您定義事物的方式,Speaker<Living>意味著一個物件具有將 aPerson | Dog作為其引數的 speak 函式。當您創建時michel,您有以下功能,如果給定一個,它可以正常作業Person:
(person) => console.log(`I have ${person.arms} arms`)
但是如果給定 a 就行不通Person | Dog,因為它試圖訪問.arms狗的財產。這種不匹配和其他不匹配就是為什么打字稿告訴你Speaker<Person>不能分配給Speaker<Living>
如果您希望陣列是物件的混合,其中一些使用Persons 作為其發言功能,其中一些使用Dogs,則其型別將是:
const speakers: Array<Speaker<Person> | Speaker<Dog>> = [michel];
編輯:如果您的Living聯合很大,或者您希望揚聲器在添加更多型別時自動更新Living,那么您可以使用以下內容獲取打字稿Speaker<Person> | Speaker<Dog>為您生成聯合:
type Distribute<T> = T extends Living ? Speaker<T> : never;
const speakers: Array<Distribute<Living>> = [michel];
// speakers is of type Array<Speaker<Person> | Speaker<Dog>>
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352811.html
標籤:javascript 数组 打字稿 打字稿泛型
上一篇:在ES6中更新物件陣列的重復值
