gpt4 book ai didi

typescript - Typescript 无法正确识别通用类型

转载 作者:行者123 更新时间:2023-12-05 04:40:59 24 4
gpt4 key购买 nike

我们有以下 TypeScript 代码:

type Option = {
name: string;
};

export const filterOptions = <T extends string>(
options: Record<T, Option>,
): unknown[] =>
Object.entries(options)
.map(([key, entry]) => ({
key,
...entry, // <--- Error: Spread types may only be created from object types.
}))
.filter(() => {
// do filtering stuff...
});

entry 的预期类型是Option , 但 TS 无法识别并假定它是 unknown .问题似乎是通用类型 T , 因为改变了 options 的类型至 Record<string, Option>更改 entry 的类型至 Option (正如预期的那样)。

这是一个TS Playground Link

我们错了什么?为什么无法正确识别类型?

最佳答案

我刚刚检查了 Object.entries() 输入:

    /**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];

选项1

看来,您可以显式地将值参数类型传递给 Object.entries()。这样它就重新定义了 typings

const filterOptions = <T extends string>(
options: Record<T, Option>,
) => {

return Object.entries<Option>(options) // added option type here!
.map(([key, entry]) => ({
key,
...entry, // It knows for sure now..
}))
.filter(() => {
// do filtering stuff...
});
}

选项 2

Record 类型使用symbols/numbersstrings 作为键。

/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};

例如,这确实有效:

const d = Symbol('somedescripton')

const a: Record<string, Option> = {
'a': {name: 'strrst'},
b: {name:'sdfsdf'},

0: {name: 'srfsdfds'},
d: {name: 'sdfsdfd'}
}

Object.entries() 会将其转换为string 键,但它仍然接受Symbolsnumbers 还有!!^因此,对于只有 string 键的 Record 类型,您可以自己键入它,以便能够省略显式转换:

type StringRecord<T extends string, K> = {[key in keyof T]: K }

const filterOptions = <T extends string>(
options: StringRecord<T, Option>,
) => {

return Object.entries(options)
.map(([key, entry]) => ({
key,
...entry, // works now..
}))
.filter(() => {
// do filtering stuff...
});
}

关于typescript - Typescript 无法正确识别通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70166541/

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