Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Last active January 13, 2017 03:54
Show Gist options
  • Save wonderful-panda/d5b5936011d0ab99041ceb99d4d44ee4 to your computer and use it in GitHub Desktop.
Save wonderful-panda/d5b5936011d0ab99041ceb99d4d44ee4 to your computer and use it in GitHub Desktop.
keyof難しい その3
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