typeofとkeyofとinの複合
typeof xはxの型を返す
object typeを受け取って、Keyのliteral unionを返す
code:ts
type Point = {
x: number;
y: number
};
keyof Point // 'x' | 'y'
mapped typeで便利
Pointのプロパティのユニオン型を指定したい
code:ts
{
x : true
y : true
}
// のようなtypeをきかたいとき次のようにかける
型パラメータPが'x'になるのがすんなり納得できない
in operator
プロパティが存在するかを返す
code:ts
type OptionsFlags<Type> = {
};
// をつくると、こんなふうに使える
type FeatureFlags = {
darkMode: () => void;
newUserProfile: () => void;
};
type FeatureOptions = OptionsFlags<FeatureFlags>;
typeの場合こうなる
code:ts
type MyType = 'foo' | 'bar';
interface MyState {
// このようにタイプを分割することもできる
}
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 {
}
こんなエラーになる(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; }'.