Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Last active November 30, 2016 04:25
Show Gist options
  • Select an option

  • Save wonderful-panda/baa7cb27d58cfd65526e1f7981c23909 to your computer and use it in GitHub Desktop.

Select an option

Save wonderful-panda/baa7cb27d58cfd65526e1f7981c23909 to your computer and use it in GitHub Desktop.
keyof 難しい
interface Test {
foo: string;
bar: number;
}
// これはOK (Testそのものだけど)
const t1: { [K in keyof Test]: Test[K] } = {
foo: "",
bar: 0
};
// これはNG
const t2: { [K in keyof Test]: { value: Test[K] } } = {
foo: { value: "" },
bar: { value: 0 }
};
// これはOK
type Value<K extends keyof Test> = { value: Test[K] };
const t3: { [K in keyof Test]: Value<K> } = {
foo: { value: "" },
bar: { value: 0 }
};
/*---------------------------------------------------------------*/
interface Test2 {
foo: { name: string, value: string };
bar: { name: string };
baz: string;
}
// Test2の定義から、{type: "foo", name: string, value: string} と {type: "bar", name: string} だけを受け入れる型を得たい
// これはコンパイルが通らない
type TestWithTypeNG1<K extends keyof Test> = {
[VK in keyof Test2[K]]: Test2[K][VK];
type: K;
}
// これはコンパイルは通るけど、ただの文字列が代入できてしまう(たぶんK="baz"で推論されるせい)
type TestWithTypeNG2<K extends keyof Test2> = Test2[K] & { type: K };
// これでOKっぽい?
type TestWithTypeOK<K extends keyof Test2, V extends Test2[K] & Object> = V & { type: K };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment