gpt4 book ai didi

javascript - Typescript 中的私有(private)继承等价物(仅包括或排除特定的类成员或属性)

转载 作者:行者123 更新时间:2023-11-30 11:05:46 25 4
gpt4 key购买 nike

在 Typescript 中模拟私有(private)继承的最佳方式是什么?具体来说,chid 类想要隐藏父类的某些成员。

例如,预期的解决方法应该实现以下目标:

CustomArray<T>Array<T> 延伸, 并隐藏特定成员说 pop()shift()仅。

let c1 = new CustomArray<number>();
c1.push(10, 20, 30, 40, 50); // okay
c1.shift(); // should error
c1.pop(); // should error
c1.sort(); // okay etc...

这是我尝试过的方法,但是 vscode 仍然允许应该是受限制的成员。

//Try to hide pop() and push():
type T1<T> = Exclude<Array<T>, 'pop'| 'push'>

// check
let x: T1<number> = [];
x.push(3); // allowed -- okay
x.pop(); // also allowed -- but wanted it to be an error

最佳答案

您不想使用继承,因为您不打算允许 CustomArray<T>以所有相同的方式使用 Array<T>可以使用。

您可以将新类型定义为 Array<T> 的函数并制作CustomArray构造函数与 Array 相同运行时的构造函数:

type CustomArray<T> = Pick<Array<T>, Exclude<keyof Array<T>, "shift" | "pop">>;
const CustomArray: new <T>() => CustomArray<T> = Array;

let c1 = new CustomArray<number>();
c1.push(10, 20, 30, 40, 50); // okay
c1.shift(); // error
c1.pop(); // error
c1.sort(); // okay

这按您要求的方式工作。但请记住,这是 Array<T> 的“浅层”转换。 .例如,sort()方法仍将返回 Array<T> , 不是 CustomArray<T> :

c1.sort().pop(); // okay

如果您真的想要一个“深度”转换,其中所有相关提及 Array<T>替换为 CustomArray<T> ,您可能需要继续并手动指定完整接口(interface),因为自动映射不太可能按您想要的方式工作:

interface CustomArray<T> {
length: number;
toString(): string;
toLocaleString(): string;
// pop(): T | undefined;
push(...items: T[]): number;
concat(...items: ConcatArray<T>[]): CustomArray<T>;
concat(...items: (T | ConcatArray<T>)[]): CustomArray<T>;
join(separator?: string): string;
reverse(): CustomArray<T>;
// shift(): T | undefined;
slice(start?: number, end?: number): CustomArray<T>;
sort(compareFn?: (a: T, b: T) => number): this;
// ... ALL the other methods, omitted for brevity
}
const CustomArray: new <T>() => CustomArray<T> = Array;
const c1 = new CustomArray();
c1.push(10, 20, 30, 40, 50); // okay
c1.shift(); // error
c1.pop(); // error
c1.sort(); // okay
c1.sort().pop(); // error

这比较乏味,但您可以对结果进行更多控制。不过,无论哪种方式都应该适合您。希望有所帮助;祝你好运!

关于javascript - Typescript 中的私有(private)继承等价物(仅包括或排除特定的类成员或属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671150/

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