gpt4 book ai didi

javascript - 为什么私有(private)/ protected 成员必须来自同一类才能实现类型兼容性?

转载 作者:行者123 更新时间:2023-12-01 03:51:21 25 4
gpt4 key购买 nike

TypeScript Handbook ,它说:

Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the instance contains a private member, then the target type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.

虽然 TypeScript 中的类型兼容性是结构化的(鸭子类型):

class Animal {
feet: number;
}

class Size {
feet: number;
}

let a: Animal = new Size; // Ok!

包含 protected /私有(private)成员的类的情况实际上是名义上的:

class Animal {
private feet: number;
}

class Size {
private feet: number;
}

let a: Animal = new Size; // Error!

谁能解释为什么 TypeScript 中公共(public)成员和 protected /私有(private)成员之间存在这种不一致吗?

最佳答案

这是有意设计的,旨在防止从不同类型访问私有(private)/ protected 成员。

来自https://github.com/Microsoft/TypeScript/issues/7755 :

Consider something like this

class Foo {
private versionNumber = 10;

public compareTo(other: Foo) {
return this.getVersion() === other.getVersion();
}

private getVersion() {
return this.versionNumber;
}
}

class Bar {
private myName = 'default;'
public compareTo(other: Bar) {
return this.myName === other.myName;
}

private getVersion() {
/* ... DANGEROUS CODE HERE ...*/
return -1;
}
}

By inspection, Bar#getVersion is never invoked -- it's a private method and there are no calls to it from the originating class. That inspection ought to be sufficient for code that doesn't actively try to work around the typechecker.

But this code does invoke Bar#getVersion:

let f = new Foo();
let b = new Bar();
f.compareTo(b);

关于javascript - 为什么私有(private)/ protected 成员必须来自同一类才能实现类型兼容性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com