gpt4 book ai didi

TypeScript:Object.keys 返回字符串 []

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:00 27 4
gpt4 key购买 nike

当使用 Object.keys(obj) 时,返回值是一个 string[],而我想要一个 (keyof obj)[].

const v = {
a: 1,
b: 2
}

Object.keys(v).reduce((accumulator, current) => {
accumulator.push(v[current]);
return accumulator;
}, []);

我有错误:

Element implicitly has an 'any' type because type '{ a: number; b: number; }' has no index signature.

带有 strict: true 的 TypeScript 3.1。 Playground :here , 请选中 Options 中的所有复选框以激活 strict: true

最佳答案

Object.keys 返回一个 string[]。这是设计使然,如本 issue 中所述

This is intentional. Types in TS are open ended. So keysof will likely be less than all properties you would get at runtime.

有几种解决方案,最简单的一种就是使用类型断言:

const v = {
a: 1,
b: 2
};

var values = (Object.keys(v) as Array<keyof typeof v>).reduce((accumulator, current) => {
accumulator.push(v[current]);
return accumulator;
}, [] as (typeof v[keyof typeof v])[]);

您还可以在 Object 中为 keys 创建一个别名,它将返回您想要的类型:

export const v = {
a: 1,
b: 2
};

declare global {
interface ObjectConstructor {
typedKeys<T>(obj: T): Array<keyof T>
}
}
Object.typedKeys = Object.keys as any

var values = Object.typedKeys(v).reduce((accumulator, current) => {
accumulator.push(v[current]);
return accumulator;
}, [] as (typeof v[keyof typeof v])[]);

关于TypeScript:Object.keys 返回字符串 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856496/

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