Last active
November 30, 2016 04:25
-
-
Save wonderful-panda/baa7cb27d58cfd65526e1f7981c23909 to your computer and use it in GitHub Desktop.
keyof 難しい
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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