【问题标题】:Force typescript to respect class types [duplicate]强制打字稿尊重类类型[重复]
【发布时间】:2021-06-24 06:41:09
【问题描述】:

我有这个代码:

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);

我不明白为什么 typescript 编译器可以使用 instance: A = new B(),因为 B 不扩展 A。如果 A 和 B 是接口,我理解,因为接口不会继续执行,但对于 Class,我不明白.

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

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

问候。

【问题讨论】:

  • B 不是A 的实例,它只是共享一个公共属性var1。然后你必须从中派生,这样他们就有了继承关系。

标签: typescript


【解决方案1】:

打字稿在你做const instance : A = new B()时没有显示任何错误的原因是因为打字稿使用结构类型,所以基本上,如果结构/形状相互一致,打字稿就可以了。

例如,如果我们有这样的事情

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 而不是A

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

【讨论】:

  • 是的,我知道,但仅适用于接口 :(。没有办法强制 Typescript 拒绝将 B 分配给 A??
猜你喜欢
  • 2017-05-16
  • 1970-01-01
  • 2017-08-12
  • 2020-04-09
  • 2017-06-10
  • 2020-04-09
  • 2021-08-31
  • 2022-06-13
  • 2019-08-04
相关资源
最近更新 更多