gpt4 book ai didi

TypeScript 类使用私有(private)函数实现类

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:38 26 4
gpt4 key购买 nike

我正在探索让一个类在 TypeScript 中实现一个类的可能性。

因此,我写了下面的代码Playground link :

class A {
private f() { console.log("f"); }
public g() { console.log("G"); }
}

class B implements A {
public g() { console.log("g"); }
}

我得到了错误:类“B”错误地实现了类“A”——类型“B”中缺少属性“f” 加上一个建议,我的意思是 扩展

所以我尝试创建一个名为 f 的私有(private)字段(public 不起作用,因为它检测到它们具有不同的访问修饰符)Playground link

现在我收到错误:类“B”错误地实现了类“A”。类型具有私有(private)属性“f”的单独声明;这让我很困惑:

  • 为什么私有(private)成员甚至很重要 - 如果我使用不同的数据结构实现相同的算法,我是否必须为了类型检查而声明名称相同的东西?
  • 为什么将 f 作为私有(private)函数实现时会出现错误?

我不会在实践中这样做,但我很好奇为什么 TS 会这样工作。

谢谢!

最佳答案

问题Microsoft/TypeScript#18499讨论了为什么在确定兼容性时需要私有(private)成员。原因是:类私有(private)成员对同一类的其他实例可见

一个remark @RyanCavanaugh 的文章特别相关且很有启发性:

Allowing the private fields to be missing would be an enormous problem, not some trivial soundness issue. Consider this code:

class Identity {
private id: string = "secret agent";
public sameAs(other: Identity) {
return this.id.toLowerCase() === other.id.toLowerCase();
}
}

class MockIdentity implements Identity {
public sameAs(other: Identity) { return false; }
}

MockIdentity is a public-compatible version of Identity but attempting to use it as one will crash in sameAs when a non-mocked copy interacts with a mocked copy.

需要说明的是,这是它会失败的地方:

const identity = new Identity();
const mockIdentity = new MockIdentity();
identity.sameAs(mockIdentity); // boom!

因此,您有充分的理由不能这样做。


作为解决方法,您可以只提取具有映射类型的类的公共(public)属性,如下所示:

type PublicPart<T> = {[K in keyof T]: T[K]}

然后你可以得到B执行不A但是PublicPart<A> :

class A {
private f() { console.log("f"); }
public g() { console.log("G"); }
}

// works
class B implements PublicPart<A> {
public g() { console.log("g"); }
}

希望对您有所帮助;祝你好运!

关于TypeScript 类使用私有(private)函数实现类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953587/

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