TypeScript - Mapped Types
2924 ワード
type OnlyBoolsAndHorses = {
[key: string]: boolean | Horse;
};
const conforms: OnlyBoolsAndHorses = {
del: true,
rodney: false,
};
optional
またはreadonly
のように、-
および+
を使用して変更することができる.// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property];
};
type LockedAccount = {
readonly id: string;
readonly name: string;
};
type UnlockedAccount = CreateMutable<LockedAccount>;
cosole.log(typeof UnlockedAccount) // {id: string; name: stinrg}
// Removes 'optional' attributes from a type's properties
type Concrete<Type> = {
[Property in keyof Type]-?: Type[Property];
};
type MaybeUser = {
id: string;
name?: string;
age?: number;
};
type User = Concrete<MaybeUser>;
console.log(typeof User); // {id: string; name: string; age: number;}
タイプスクリプト4.1のバージョンからマッピングを開始するタイプは、as
を使用して再マッピングできます.type MappedTypeWithNewProperties<Type> = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}
type Getters<Type> = {
[Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
interface Person {
name: string;
age: number;
location: string;
}
type LazyPerson = Getters<Person>;
console.log(tpyeof LazyPerson)
/*. getName: () => string;
getAge: () => number;
getLocation: () => string; */
Reference
この問題について(TypeScript - Mapped Types), 我々は、より多くの情報をここで見つけました https://velog.io/@changchanghwang/TypeScript-Mapped-Typesテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol