Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Created December 14, 2016 00:56
Show Gist options
  • Select an option

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

Select an option

Save wonderful-panda/51f516f9bfcd0b8d6f652f2791dccb43 to your computer and use it in GitHub Desktop.
keyofやっぱり難しい
interface Base {
foo: { [key: string]: any };
bar: any;
baz: any;
}
interface Hoge {
hoge: string;
fuga: string;
}
// Baseを継承して、fooの型の制約をきつくしたい
interface Extend1 extends Base {
foo: Hoge
}
interface Extend2<T> extends Base {
foo: T
}
interface Extend3 extends Base {
foo: { [K in keyof Hoge]?: Hoge[K] }
}
interface Extend4<T> extends Base {
foo: { [K in keyof T]?: T[K] } // もしくは Partial<T>
}
// Extend4だけエラー
// error TS2430: Interface 'Extend4<T>' incorrectly extends interface 'Base'.
// Types of property 'foo' are incompatible. Type '{ [K in keyof T]?: T[K]; }' is
// not assignable to type '{ [key: string]: any; }'.
// やりたいことは↓でできるんだけど
type Extend5<T> = Base & { foo: Partial<T> };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment