如果我按如下方式定义我的类型,它将遵循我想要的行为。
interface Foo {}
interface Bar {
a: string;
b: boolean;
c: Foo;
}
type x = keyof Bar; // "a" | "b" | "c"
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试添加索引签名,它会丢失我所有的预定义成员。
interface Bar {
[index: string]: any;
}
type x = keyof Bar; // string | number
Run Code Online (Sandbox Code Playgroud)
有没有办法在 TypeScript 中正确地做到这一点?
类似于:
type x = Exclude<Bar, { [index: string]: any }>; // never
Run Code Online (Sandbox Code Playgroud)
编辑 我尝试了类似于 Jake 的解决方案并得到了这个:
interface Indexable<T> {
[index: string]: any;
}
type BaseType<T> = T extends Indexable<infer U> ? U : never;
interface …Run Code Online (Sandbox Code Playgroud) typescript ×1