javascript - 打字稿:如何注释一个类(而不是类实例)的类型?
问题描述
假设有一个模型类,如:
export abstract class Target {
id!: number;
name!: string;
}
export class Target1 extends Target {
name = 'target1';
id: number;
kind: string;
constructor(id: number, kind: string) {
super();
this.id = id;
this.kind = kind;
}
static getForm(){
return new FormGroup({...});
}
}
export class Target2 extends Target {
name = 'target2';
id: number;
address: string;
constructor(id: number, address: string) {
super();
this.id = id;
this.address = address;
}
static getForm(){
return new FormGroup({...});
}
}
....
export class TargetN extends Target {}
type Measure = {
type: string;
target: any; // Here is what I need to correct the type
}
const measures: Measure[] = [
{ type: 'measure1', target: Target1},
{ type: 'measure2', target: Target2},
...
{ type: 'measureN', target: TargetN},
];
在表单中,我允许用户输入address
或kind
根据用户选择的情况,measures.type
然后我将实例化一个新target
的,如下所示:
const inputValue = 'http://localhost:3000';
const selectedType = measures[0].type;
const measure = measures.find(m => m.type === selectedType)!;
const target = new measure.target(1, inputValue);
const form = measure.target.getForm();
console.log(target.kind); //
...
一切正常。但是让我烦恼的是我不知道如何将正确的类型放在Measure -> target
而不是any
:
type Measure = {
type: string;
target: any; // ???
}
如果我给它一个Target
像下面这样的类型:
type Measure = {
type: string;
target: Target;
}
然后我会得到错误
Did you mean to use 'new' with this expression?
而且,如果我typeof
像下面这样给出它:
type Measure = {
type: string;
target: typeof Target;
}
然后我会得到错误
Type 'typeof Target1' is not assignable to type 'typeof Target'.
如何将any
目标中的类型替换为另一种特异性类型?
如果我使用ThisType它看起来不错
type Measure = {
type: string;
target: ThisType<Target>;
}
但static method
里面Target1 or Target2
会抛出错误
Property 'getForm' does not exist on type 'ThisType<Target>'.
我还尝试了如下必需的:
type RequiredTarget = Required<typeof Target>;
type Measure = {
type: string;
target: RequiredTarget;
}
但它也不起作用。
我很感激你的帮助。
解决方案
我将通过以下方式解决此问题:
type S = string;
type I = number;
interface IY {
type?: string;
target?: S | I;
}
type Y = IY
const U: Y = { type: "U", target: "1" }
const V: Y = { type: "V", target: 2 }
const X: Y = {}
推荐阅读
- kubernetes - 在每个集群的基础上覆盖 helm 子图中的值的最佳实践是什么?
- javascript - 标记复选框已完成 - 反应
- ruby-on-rails - 当作为参数传递给另一个方法时,HTTParty::Response 被转换为 Hash
- sql-server - SQL Server:选择与当前列具有相同列值的以下(序列)行等于参数
- jsdoc2md - jsdoc2md:使用多个文件时如何排序功能?
- blockly - 如何使用 Blockly 生成 JavaScript 函数作用域变量?
- oracle-sqldeveloper - 重命名 plsql 包后 Oracle SQL Developer 冻结
- android - “离子科尔多瓦运行安卓”的离子科尔多瓦运行失败
- jena - 未找到 Apache Jena 命令
- java - 在我编译的 jar 中包含一些依赖项