Last active
January 13, 2017 03:54
-
-
Save wonderful-panda/d5b5936011d0ab99041ceb99d4d44ee4 to your computer and use it in GitHub Desktop.
keyof難しい その3
This file contains 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 Context { prop1: string; } | |
type Handlers<T> = { | |
[K in keyof T]: (ctx: Context, payload: T[K]) => void | |
}; | |
function test<T>(handlers: Handlers<T>): Partial<T> { | |
return {} as any; | |
} | |
const t = test({ | |
foo(ctx, payload: number) { | |
// ctxがanyとして推論されてしまい、存在しないpropertyにアクセスしてもエラーにならない | |
console.log(ctx.prop2); | |
} | |
}); | |
// Tが { foo: number } であることはちゃんと推論できている | |
console.log(t.foo && t.foo.toFixed()); | |
/* | |
* Workaround | |
*/ | |
type Handlers2<T> = { | |
[K in keyof T]: (ctx: Context, payload: T[K]) => void | |
} & { | |
[key: string]: (ctx: Context, payload: any) => void | |
}; | |
function test2<T>(handlers: Handlers2<T>): Partial<T> { | |
return {} as any; | |
} | |
const t2 = test2({ | |
foo(ctx, payload: number) { | |
// ctxがContextとして推論されているので、ちゃんとエラーになる | |
console.log(ctx.prop2); | |
} | |
}); | |
// Tの推論も問題ない | |
console.log(t2.foo && t2.foo.toFixed()); | |
// Tを推論させずに、明示的に指定すれば問題は起こらない | |
test<{ foo: number }>({ | |
foo(ctx, payload) { | |
// ctxがContextとして推論されているので、ちゃんとエラーになる | |
console.log(ctx.prop2); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment