typescript - 打字稿如何使用具有字符串类型参数的方法声明类,该参数是特定类型的派生类的属性名称
问题描述
我有一个基类,其方法可从派生类调用,您可以在派生类中提供必须是特定类型的派生属性名称之一。然后对属性值进行操作。我希望能够指定这种特定类型。(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>'.
}
}
解决方案
您的问题是 polymorphicthis
的行为类似于泛型类型参数,并且在 的实现内部Test
是this
一个尚未指定/未解析的类型参数,编译器无法对其进行太多验证。(有一些 GitHub 问题提到了这一点,至少顺便提及;参见microsoft/TypeScript#41495,microsoft/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
}
推荐阅读
- css - 页面在小屏幕上无法正常工作
- ios - 关闭尚未编辑的视图时崩溃 - SwiftUI
- python - 整数的不同分区,不包括重复组合
- java - 如何使用 java、JSON 获取一个国家的 covid 信息
- java - 将项目导出到 jar 文件后,我的项目无法正常工作
- python - 使用 MOSES 或 PHRASER 在 python 中翻译?
- c# - 如何创建状态图
- asp.net-core - 在 Entity Framework Core 中为多个上下文生成脚本,带有数据库引用
- cross-compiling - Bazel 对来自 cc_library 的 genrule 的依赖没有建立
- angular - localStorage.getItem('user') 为空