[英]How can I express a Constructor Function with static variables in Typescript?
我想在另一个文件中访问以下类:
export class Person {
constructor() {}
static getDatabaseId(): string {
return '...';
}
}
它是注入的,而不是实际导入的。 我想表明它是一个构造函数,并且可以创建Person类型的新实例。 这是我尝试的:
let PersonConstructor: {new(): Person};
// inject Person constructor function
beforeEach(inject((_Person_) => {
PersonConstructor = _Person_;
}));
// create a new instance but also access the static variables
const p: Person = new PersonConstructor();
PersonConstructor.getDatabaseId(); // "property does not exist"
编译器不再抱怨要从Person实例化新实例,但是现在它现在也不知道Person的静态变量,因为它们在新声明的类型上丢失了。
如何正确键入?
我不确定您的代码的最终目标是什么。 从TypeScript文档开始,要实现的语法的一种可能用法是修改类的static
成员,并使用新的静态成员创建新实例。
如果您要执行此操作,则正确的代码将如下所示
let PersonConstructor: typeof Person = Person;
// create a new instance but also access the static variables
const p: Person = new PersonConstructor();
PersonConstructor.getDatabaseId(); // Also OK and you my change it. Original Person will not get it changed.
您可以使用构造函数签名方法,但需要添加需要访问的任何其他成员。
import {Person} from './Person';
let PersonConstructor: {
new(): Person
getDatabaseId(): string
} = Person;
// create a new instance but also access the static variables
const p: Person = new PersonConstructor();
PersonConstructor.getDatabaseId(); // "property does not exist"
或者,如果要使用与Person
完全相同的类型(构造函数签名和所有静态变量),则可以只使用typeof Person
:
import {Person} from './Person';
let PersonConstructor: typeof Person = Person;
// create a new instance but also access the static variables
const p: Person = new PersonConstructor();
PersonConstructor.getDatabaseId(); // "property does not exist"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.