[英]Typescript: What is a mapped type and how is this useful?
在 Typescript 中,我們有時希望基於其他類型構建類型。 映射類型允許我們以非常簡潔的方式基於現有類型生成新類型,這使我們遵守不重復自己的原則
自定義屬性:
type customProperties = {
[key: string]: string | boolean;
};
const conforms: customProperties = {
str: 'foo',
bool: true,
// int: 123 > Error Type 'number' is not assignable to type 'string | boolean'.
};
映射類型:
type Person = {
name: string;
age: string;
};
// Demo only >> TS has a builtin Readonly, use that
type myReadonly<Type> = {
readonly [Property in keyof Type]: Type[Property];
};
// Demo only >> TS has a builtin Partial, use that
type myPartial<Type> = {
[Property in keyof Type]?: Type[Property];
};
type ReadonlyPerson = myReadonly<Person>
type PartialPerson = myPartial<Person>
請注意,映射類型使用語法[]: type
of custom properties。 自定義屬性和映射類型的區別如下:
[Property in keyof Type]
語法對現有類型的屬性進行迭代。 它將現有類型的所有屬性映射到您可以根據需要自定義的新類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.