【发布时间】:2021-12-20 05:27:15
【问题描述】:
想象一下班级:
class Person {
name = "Ann";
sleep() { /*...*/ }
eat() { /*...*/ }
}
现在我想创建一个只提取方法的类型:
// should work:
const personMethods: MethodsOf<Person> = { sleep() {}, eat() {} };
const names: keyof MethodsOf<Person>[] = ['sleep', 'eat'];
// should fail:
const personMethods: MethodsOf<Person> = { notAPersonMethod() {} };
const names: keyof MethodsOf<Person>[] = ['not', 'existing', 'methods'];
我在 typescript 文档中找不到任何内容,到目前为止我的尝试都失败了。我试过了:
type MethodKeys<
Type extends object,
Key extends keyof Type,
> = keyof Record<Type[Key] extends AnyFn ? Key : never, any>;
type Methods<Type extends object> = {
[Property in MethodKeys<Type, keyof Type>]: Type[Property];
};
const test: MethodKeys<Person> = 'name'; // works, but shouldn't :(
const test2: Partial<Methods<Person>> = { name: 'Ann' }, // works too :/
感谢您的帮助!
【问题讨论】:
-
我想你的意思是
Array<keyof MethodsOf<Person>>或(keyof MethodsOf<Person>)[]那里。注意优先级,keyof MethodsOf<Person>[]在数组上应用keyof。
标签: typescript types mapped-types conditional-types