[英]TypeScript - Using Generics to Create a Custom Type
我正在使用一個中間步驟來創建一個類型 ,該類型的屬性鍵必須與指定接口的鍵相同
// 1. Create Interface
interface IDetail {
name: string;
enabled: boolean;
}
// 2. Create a 'type' that has properties that match the properties of an interface
type DetailType = {
[key in keyof IDetail]: any
}
// 3. Apply the type to an object literal
const control: DetailType = {
name: [],
enabled: []
}
我經常重復這種模式,我想知道是否有一種方法可以概括第二步-可能使用泛型 ?
好吧,您可以使您的類型通用:
interface IDetail {
name: string;
enabled: boolean;
}
type Generic<T> = { [key in keyof T]: any };
const controlGeneric: Generic<IDetail> = {
name: [],
enabled: []
};
您可以創建一個特殊的泛型類型:
type WrapMyType<T, V> = { [key in keyof T]: V };
const control: WrapMyType<IDetail, any> = {
name: [],
enabled: [],
};
如果您不想丟失類型,可以使用此方法
type DetailType<T> = { [key in keyof T]: T[key] };
const control: DetailType<IDetail> = {
name: [], // must be string
enabled: [] // must be boolean
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.