如何将UNINITIALISED类应用于Typescript中的对象



我希望这个代码示例对我要做的事情足够清楚

请注意,这是一个简化的测试用例,用来演示我遇到的核心问题。我不想知道如何使这个例子更简单。我想知道如何阻止TypeScript抱怨。我也不想使用any类型。

// start with a class
class HelloWorld {
hello = 'hello'
world(): string {
return this.hello + ' world'
}
}
// Create an interface for an object
interface Greeting {
Hello: HelloWorld
}
// The interface is applied to an object
// The class is applied to a value inside the object
// Note that it is an UNINITIALISED class
const greet: Greeting = {
// ERROR: Type 'typeof HelloWorld' is missing the following properties
// from type 'HelloWorld': hello, world ts(2739)
Hello: HelloWorld,
}
// Later in the code you initialise it like this
// ERROR: This expression is not constructable.
// Type 'HelloWorld' has no construct signatures.ts(2351)
const greeting = new greet.Hello()
console.log(greeting.world()) // "hello world"

您将普通类视为实例的接口。它只适用于使用new关键字声明的实例。要在接口中正确使用类类型,请将类转换为类型或接口,这样TypeScript就会知道你在推断类本身,而不是它的实例。

以下是如何为类的类和实例声明接口

interface Greeting {
// declaring type for the class itself
Hello: typeof HelloWorld,
// declaring the type for it's instance
hello: HelloWorld
}
const greet: Greeting = {
// Assigning the class itself
Hello: HelloWorld,
// Assigning an instances of HelloWorld
hello: new HelloWorld()
}
const greeting = new greet.Hello()
// `greeting` is now identical to `greet.hello`

最新更新