首页 > 解决方案 > 打字稿如何使用具有字符串类型参数的方法声明类,该参数是特定类型的派生类的属性名称

问题描述

我有一个基类,其方法可从派生类调用,您可以在派生类中提供必须是特定类型的派生属性名称之一。然后对属性值进行操作。我希望能够指定这种特定类型。(keyof 显然是不够的)

可以输入这个吗?

这不起作用

type PropertyNamesOfType<T extends {},TPropertyType> = {
 [P in keyof T]: TPropertyType extends T[P] ? P : never
}[keyof T]

declare class TypeUsingBoolPropertyOfDerived{
  withArgKeyOfTypeBoolean<E extends PropertyNamesOfType<this, boolean>>(arg:E):void;
}

class Test extends TypeUsingBoolPropertyOfDerived{
  boolProp:boolean
  stringProp:string
  try(): void {
   this.withArgKeyOfTypeBoolean('boolProp');
   //Argument of type 'string' is not assignable to parameter of type 'PropertyNamesOfType<this, boolean>'.
 }
}

标签: typescripttypescript-declarations

解决方案


您的问题是 polymorphicthis的行为类似于泛型类型参数,并且在 的实现内部Testthis一个尚未指定/未解析的类型参数,编译器无法对其进行太多验证。(有一些 GitHub 问题提到了这一点,至少顺便提及;参见microsoft/TypeScript#41495microsoft/TypeScript#41181

在外面 Test,你只是使用一个实例Test而不是实现它,编译器将替换它Test并且this所有行为都将按预期运行,比如

new Test().withArgKeyOfTypeBoolean("boolProp"); // okay

这导致了一种可能的解决方法:在内部try(),首先将 (generic-like) 分配给this(specific) Test,然后调用withArgKeyOfTypeBoolean()它:

try(): void {
    const thisTest: Test = this;
    thisTest.withArgKeyOfTypeBoolean('boolProp'); // okay
}

Playground 代码链接


推荐阅读