gpt4 book ai didi

typescript - 如何编写一个类型保护,它接受一个泛型类型 T 的对象和一个字符串参数,并检查该字符串是否为 keyof T 类型?

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

我有一个类型为 MyObject 的对象,它有两个字符串属性。

interface MyObject {
a: number,
b: string,
}

const myObject = {
a: 5,
b: 'str'
}

然后我有一个接受字符串的函数,我希望能够访问由字符串参数指定的上述对象的属性。我想做的是在访问属性之前使用类型保护来检查字符串是否是对象的键。这里有必要做一些检查,因为参数只是一个字符串,对象没有索引签名。

如果我制作一个特定版本来检查这种特定类型的对象 (MyObject),它会起作用:

// specific version
const isValidPropertyForMyObject = (property: string): property is keyof MyObject => Object.keys(myObject).indexOf(property) !== -1

const getProperty1 = (property: string) => {
if (isValidPropertyForMyObject(property)) {
myObject[property]
}
}

但是,如果我希望能够传入一个具有泛型类型的对象和一个字符串参数,并检查该属性实际上是该对象的键怎么办?这是我的尝试:

const isValidMethodForHandler = <T extends { [i: string]: any }>(handler: T) => (
method: string
): method is keyof T => Object.keys(handler).indexOf(method) !== -1;


const getProperty = (property: string) => {
// const acceptedProperties = ["a", "b"];
// if (acceptedProperties.indexOf(property) !== -1) {
// myObject[property]
// }

if (isValidMethodForHandler(myObject)(property)) {
myObject[property]
}
}

问题出在类型保护中:

A type predicate's type must be assignable to its parameter's type. Type 'keyof T' is not assignable to type 'string'. Type 'string | number | symbol' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.(2677)

最佳答案

答案基于 TypeScript 问题跟踪器中的这个线程 here .

关于上述问题中特定 TypeScript 错误的解释在 this other question 中。

我的示例代码的解决方案是:

const isValidMethodForHandler = <T extends { [i: string]: any }>(handler: T) => (
method: string
): method is Extract<keyof T, string> => Object.keys(handler).indexOf(method) !== -1;

const getProperty = (property: string) => {
if (isValidMethodForHandler(myObject)(property)) {
myObject[property]
}

keyof 返回所有已知的键,这些都是 string |编号 |符号

要仅获取字符串属性,请使用Extract

关于typescript - 如何编写一个类型保护,它接受一个泛型类型 T 的对象和一个字符串参数,并检查该字符串是否为 keyof T 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58985630/

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