相关疑难解决方法(0)

TS接口不强制实现者使用功能签名

interface test{
    foo(boo:string);
}
class coo implements test{
    foo(){

    }
}
Run Code Online (Sandbox Code Playgroud)

playGround 中,虽然函数签名不像接口所说的那样但这并不会生成和错误,接口的预期行为是强制签名.

为什么会这样?

谢谢

interface signature typescript

8
推荐指数
1
解决办法
834
查看次数

扩展抽象类的类是什么类型?

我有一个抽象类,以及在数组中扩展它的类。我该输入什么数组?

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

7
推荐指数
1
解决办法
1867
查看次数

TypeScript中的原子类型判别(标称原子类型)

我只是好奇者,有没有一种方法可以区分原子类型以提高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)

typescript

6
推荐指数
1
解决办法
182
查看次数

标签 统计

typescript ×3

interface ×1

signature ×1