我有一个具有一些属性和方法的对象。我如何给予它一个只接受它的另一个方法的名称的方法?
例如,考虑User
类中的command
方法。我们希望command
接受另一个方法的名称。使用keyof this
将可接受的类型缩小到User
属性名称;我们如何进一步缩小到User
* 方法 * 名称,而不硬编码它们?
class User {
nameFirst: string;
nameLast: string;
command(commandName: keyof this) {
this[commandName].call(this);
}
sink() {}
swim() {}
}
const alice = new User();
alice.command(`swim`); // Accepts `nameFirst` | `nameLast` | `command` | `sink` | `swim`; we want it to accept only `sink` and `swim`
字符串
3条答案
按热度按时间avwztpqn1#
不知道你具体想做什么,但这对你的用例有用吗?
字符串
1qczuiv02#
若要将命令方法的可接受类型限制为仅使用User方法名称,而不对其进行硬编码,可以将条件类型和Map类型组合在一起使用合并。
字符串
iqih9akk3#
TypeScript没有内置的
KeysMatching<T, V>
类型操作符来提取T
类型的键,其值与microsoft/TypeScript#48992中请求的其他类型V
匹配,但您可以自己实现一个适用于某些用例的类型操作符,例如:字符串
然后,从概念上讲,您可以将
commandName
的类型设置为KeysMatching<User, ()=>void>
,以便它只允许零参数方法。(因为commandName
的类型取决于User
的类型,而User
的类型又取决于command
的类型,而command
的类型又取决于commandName
的类型)。你可以通过从键中省略"command"
来避免这一点,使用Omit
实用程序类型:型
Playground链接到代码