[英]Typescript extending interface with generic type causes subtype of constraint error
[英]TypeScript: Reference subtype of type definition (interface)
我在 TypScript 中使用以下類型:
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
現在我想創建一個與屬性vocabulary
相同類型的變量,嘗試以下操作:
var vocabs : ExerciseData.vocabulary[];
但這行不通。 是否可以以某種方式引用子類型? 或者我必須做這樣的事情?
interface ExerciseData {
id : number;
name : string;
vocabulary : Vocabulary[];
}
interface Vocabulary {
from : string;
to : string;
}
var vocabs : Vocabulary[];
非常感謝提示。
您可以使用在 TypeScript 2.1 中添加的查找類型來引用接口子類型:
interface ExerciseData {
id: number;
name: string;
vocabulary: Array<{
from: string;
to: string;
}>;
}
type Name = ExerciseData['name']; // string
這些查找類型也可以鏈接。 因此,要獲取詞匯項的類型,您可以這樣做:
type Vocabulary = ExerciseData['vocabulary'][number]; // { from: string; to: string; }
或者更多的鏈接, from
字段:
type From = ExerciseData['vocabulary'][number]['from']; // string
對於復雜的場景,也可以將查找類型基於另一種類型。 例如,在字符串文字聯合類型上:
type Key = 'id' | 'name';
type FieldTypes = ExerciseData[Key]; // number | string
這些天我發現它的工作方式如下:
interface User {
avatar: string;
}
interface UserData {
someAvatar: User['avatar'];
}
如果您不想導出所有內容,則非常有用。
不完全是您想要的,但您可以使用typof 關鍵字解決此問題,但前提是您有一個聲明為接口類型的var,如下所示。 請注意,我認為您在上一個代碼塊中所做的要好得多:)
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
var x: ExerciseData;
var vocabs : typeof x.vocabulary[];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.