typeofとkeyofとinの複合
typeof xはxの型を返す
typeof - JavaScript | MDN
keyof Type(TS)
object typeを受け取って、Keyのliteral unionを返す
code:ts
type Point = {
x: number;
y: number
};
keyof Point // 'x' | 'y'
TypeScript: Documentation - Keyof Type Operator
mapped typeで便利
TypeScript: Documentation - Mapped Types
Pointのプロパティのユニオン型を指定したい
code:ts
{
x : true
y : true
}
// のようなtypeをきかたいとき次のようにかける
P in keyof Point : boolean
型パラメータPが'x'になるのがすんなり納得できない
参考:https://www.wakuwakubank.com/posts/756-typescript-in-typeof-keyof/
in operator
プロパティが存在するかを返す
in operator - JavaScript | MDN
code:ts
type OptionsFlags<Type> = {
Property in keyof Type: boolean;
};
// をつくると、こんなふうに使える
type FeatureFlags = {
darkMode: () => void;
newUserProfile: () => void;
};
type FeatureOptions = OptionsFlags<FeatureFlags>;
https://runebook.dev/ja/docs/typescript/2/mapped-types
typeの場合こうなる
code:ts
type MyType = 'foo' | 'bar';
interface MyState {
// このようにタイプを分割することもできる
foo: {key in MyType : string }
}
const obj : MyState = {
foo : {foo: 'foo'}
}
を実行するとobjにfoo.barがないのでエラーになる
Property 'bar' is missing in type '{ foo: string; }' but required in type '{ foo: string; bar: string; }'.
ここで上の例のようにkeyofを使ってみると
code:ts
interface MyState {
foo: {key in keyof MyType :string }
}
こんなエラーになる(MyTypeはキーがないのでこうなるのだと思う)
code:zsh
Type '{ foo: string; bar: string; }' is not assignable to type '{ x: number: string; toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastIndexOf: string; localeCompare: string; match: string; replace: string; search: string; ... 32 more ...; Symbol.iterator: string; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ x: number: string; toString: string; charAt: string; charCodeAt: string; concat: string; indexOf: string; lastIndexOf: string; localeCompare: string; match: string; replace: string; search: string; ... 32 more ...; Symbol.iterator: string; }'.