interface test{
foo(boo:string);
}
class coo implements test{
foo(){
}
}
Run Code Online (Sandbox Code Playgroud)
在playGround 中,虽然函数签名不像接口所说的那样但这并不会生成和错误,接口的预期行为是强制签名.
为什么会这样?
谢谢
我有一个抽象类,以及在数组中扩展它的类。我该输入什么数组?
abstract class AbstractClassToExtend {
constructor() { console.log("hello") }
}
class One extends AbstractClassToExtend {}
class Two extends AbstractClassToExtend {}
const array = [One, Two] // what do i type this array?
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了const array: typeof AbstractClassToExtend[] = [One, Two],但是当创建数组中的类之一的实例时,
new array[0]()
Run Code Online (Sandbox Code Playgroud)
它给出了一个错误:
error TS2511: Cannot create an instance of an abstract class.
Run Code Online (Sandbox Code Playgroud)
我正在使用 Typescript 4.3.2。
我只是好奇者,有没有一种方法可以区分原子类型以提高TypeScript中的类型安全性?
换句话说,下面有一种方法可以复制行为:
export type Kilos<T> = T & { discriminator: Kilos<T> }; // or something else
export type Pounds<T> = T & { discriminator: Pounds<T> }; // or something else
export interface MetricWeight {
value: Kilos<number>
}
export interface ImperialWeight {
value: Pounds<number>
}
const wm: MetricWeight = { value: 0 as Kilos<number> }
const wi: ImperialWeight = { value: 0 as Pounds<number> }
wm.value = wi.value; // Should give compiler error
wi.value = wi.value * 2; // Shouldn't error, …Run Code Online (Sandbox Code Playgroud)