javascript - 我如何在 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 的静态变量,因为它们在新声明的类型上缺失。
这该如何正确打字?
答案#1
我不确定你的代码的最终目标是什么。根据 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.
答案#2
你可以使用构造函数签名方法,但你需要添加你需要访问的任何其他成员。
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"
