gpt4 book ai didi

javascript - 原型(prototype)上内置方法的覆盖类型

转载 作者:行者123 更新时间:2023-12-04 07:29:56 25 4
gpt4 key购买 nike

hasOwnProperty 的默认类型是 hasOwnProperty(v: PropertyKey): boolean; .但是,这使我无法执行以下操作:

const obj = { a: 1 };

function foo(str: string) {
if (obj.hasOwnProperty(str)) {
console.log(obj[str]);
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; }'.
}
}
覆盖 obj.hasOwnProperty 的类型,我补充说:
interface Object {
hasOwnProperty<T extends ObjectOf<any>>(this: T, key: any): key is keyof T;
}
这适用于 obj.hasOwnProperty(key) ,但不是 Object.prototype.hasOwnProperty.call(obj, key) .如何覆盖 hasOwnProperty当我使用第二种方法调用它时的类型?
编辑:为了澄清,即使有覆盖,以下内容也不起作用:
const obj = { a: 1 };

function foo(str: string) {
if (Object.prototype.hasOwnProperty.call(obj, str)) {
console.log(obj[str]);
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; }'.
}
}

最佳答案

完整更新
我错了,我只覆盖了call方法。
很抱歉给你提供了不好的例子。
使用我之前的代码,调用 Object.prototype.[any prototype method].call会像打字员一样行事,这是错误的。
上一页 错了代码:

interface CallableFunction extends Function {

call<T, Prop extends string, R>(this: (this: T, property: Prop) => R, thisArg: T, property: Prop): thisArg is T & Record<Prop, string>;
}

以上代码表示 Object.prototype.propertyIsEnumerable.call将充当打字员,因为我只输入了 call .
工作示例


type Tag = { [prop: `tag${number}`]: never }

interface Object {
hasOwnProperty(v: PropertyKey): boolean & Tag
}

interface CallableFunction extends Function {
call<
T,
Prop extends string,
R extends boolean & Tag
>(this: (this: T, property: Prop) => R, thisArg: T, property: Prop): thisArg is T & Record<Prop, string>;
}

declare const obj: { name?: string, surname?: number }

if (Object.prototype.hasOwnProperty.call(obj, 'name')) {
const test = obj.name // string
}

if (Object.prototype.propertyIsEnumerable.call(obj, 'name')) {
const test = obj.name // string | undefined
}

Playground
它是如何工作的 ?
我创建了一个品牌类型 Tag并与 hasOwnProperty 相交返回类型。
它给了我什么? call方法能够推断出 hasOwnProperty 的返回类型.这是知道调用了哪个原型(prototype)方法的唯一方法。
然后,我将约束添加到 R泛型类型。 R是从原型(prototype)方法推断的返回类型。在我们的例子中是 boolean & Tag .这就是 call方法能够找出我们调用了 hasOwnProperty .

关于javascript - 原型(prototype)上内置方法的覆盖类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68001036/

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