[英]Typescript extract from mapped type, the specific value of the union type of the props
我的目標是使用 ValueType 作為“翻譯器”獲得具有正確類型屬性的 output 變量。 我的問題是我不能將 unionType 的特定值作為 ValueType 參數傳遞,只能傳遞 unionType 本身。 結果我得到所有屬性都可以采用 ValueType 提供的所有可能值。
enum Kind {
AsIs = 'AsIs',
Fields = 'Fields',
Category = 'Category'
};
interface Type {
field: string;
category: number;
color: string;
}
type KindSetting<T> = { [k in keyof T]: Kind };
const a: KindSetting<Type> = {
field: Kind.Fields,
category: Kind.Category,
color: Kind.AsIs,
};
type ValueType<T extends Kind> =
T extends Kind.Fields ? boolean :
T extends Kind.AsIs ? string :
T extends Kind.Category ? number :
never;
type Output<T> = { [K in keyof T]: ValueType<KindSetting<T>[K]> }
const output: Output<Type> = {
field: '',
category: 5,
color: ''
};
這是typescript 操場上的代碼
據我所知,您正在強制output
a
變量類型,即{ field: boolean; category: number; color: string }
{ field: boolean; category: number; color: string }
{ field: boolean; category: number; color: string }
。
您必須將a
聲明為其文字類型: { field: Kind.Fields }
,而不是一般的{ field: Kind }
,以與output
一起使用; 否則,一般的Kind
類型將產生boolean | string | number
boolean | string | number
boolean | string | number
類型。 Output
類型也需要稍微改變一下。
順便說一句,我想介紹一種替代您的ValueType
類型的方法。
const a = {
field: Kind.Fields,
category: Kind.Category,
color: Kind.AsIs,
} as const;
type ValueType<T extends Kind> =
T extends Kind.Fields ? boolean :
T extends Kind.AsIs ? string :
T extends Kind.Category ? number :
never;
interface KindMapping {
[Kind.Fields]: boolean;
[Kind.AsIs]: string;
[Kind.Category]: number;
}
type Output<T extends KindSetting<T>> = { [K in keyof T]: KindMapping[T[K]] };
// ValueType<T[K]> can also be used instead of KindMapping[T[K]]
const output: Output<typeof a> = {
field: '', // error, must be boolean
category: 5,
color: ''
};
如果您不在其他地方a
變量,則可以將其設為接口/類型而不是具體變量。
interface A {
field: Kind.Fields;
category: Kind.Category;
color: Kind.AsIs;
}
const output: Output<A> = { // same effect
field: '',
category: 5,
color: '',
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.