下面是我的问题的一个例子(在ts游乐场的演示)
type Tkey = 'foo' | 'bar' | 'defaultKey'
const typedObject: Record<Tkey, Boolean> = {
'foo': true,
'bar': false,
'defaultKey': true
}
// type does not persist string narrowing
const entries = Object.entries(typedObject) // [string, Boolean][]因此,key in [key, values]是string型,而不是Tkey型。

作为一种解决办法,您可以在事后手动强制,但最好在操作期间定义类型。
const typedEntries = entries as [Tkey, Boolean][]发布于 2021-08-11 13:48:52
TypeScript的本机定义文件包含Object.entries的以下内容
entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];
entries(o: {}): [string, any][];您获得所需行为的唯一机会是使用以下内容覆盖此定义:
interface YourOwnObject {
entries<T>(o: { [K in keyof T]: T[K] }): [keyof T, T[keyof T]][];
}
(<YourOwnObject>Object).entries(typedObject).forEach(([key, values]) => {
// ...
})发布于 2021-11-11 00:13:40
您可以通过添加包含两个泛型类型参数的自己的对象定义来扩展默认类型记录库。
在项目根目录中添加以下globals.d.ts文件:
interface ObjectConstructor {
entries<TKey extends PropertyKey, TVal>(o: Record<TKey,TVal>): [TKey, TVal][];
keys<TKey extends PropertyKey>(obj: Record<TKey,any>): TKey[];
}然后像这样使用它:
const entries = Object.entries<ObjKeys, Boolean>(myObj) // [ObjKeys, Boolean][]
const keys = Object.keys<ObjKeys>(myObj) // ObjKeys[]https://stackoverflow.com/questions/68742597
复制相似问题