强制打字稿尊重类类型

时间:2021-03-27 16:48:16

标签: typescript

我有这个代码:

class A {
    public var1: string = 'var1';
}

class B {
    public var1: string = 'var1';
    public var2: string = 'var2';
}

const instance: A = new B();
console.log(instance instanceof A);

我不明白为什么打字稿编译器对 instance: A = new B() 没问题,因为 B 不扩展 A。如果 A 和 B 是接口,我理解,因为接口不会继续执行,但对于类我不'不明白。

最后一行返回“false”,证明A不是B!

有事情要做吗?编译器选项?带有泛型的代码?...

问候。

1 个答案:

答案 0 :(得分:1)

当你执行 const instance : A = new B() 时,typescript 没有显示任何错误的原因是因为 typescript 使用结构类型,所以基本上,如果结构/形状彼此一致,typescript 就可以了。

例如,如果我们有这样的东西

class A {
  foo() : boolean { return true }
}

class B {
 foo() : boolean { return true }
}

const bar : A = new B()

由于结构的原因,typescript 编译器将上述内容视为同一件事,但是一旦更改结构,编译器就会对其进行标记。

class AA {
  foo() : boolean { return true }
}

class BB {
 foo() : string { return "true" }
}

const foobar : AA = new BB()

您会在 tsc Type 'BB' is not assignable to type 'AA'. The types returned by 'foo()' are incompatible between these types. Type 'string' is not assignable to type 'boolean'

中看到此类错误

回到您的示例,B 具有 A 的确切结构,因为 public var1: string 出现在 BA 中,所以 B可以分配给 A,但是当你反过来,

const instance: B = new A()

编译器会标记代码,因为 A 不完全符合 B 的结构,因为 public var2: string 出现在 B 而不是 {{1} }.

在 C++、Java 和少数其他使用名义类型的语言中,编译器会标记代码的类型。