打字稿:Object.keys 返回字符串[] [英] TypeScript: Object.keys return string[]
问题描述
当使用Object.keys(obj)
时,返回值是一个string[]
,而我想要一个(keyof obj)[]
代码>.
When using Object.keys(obj)
, the return value is a string[]
, whereas I want a (keyof obj)[]
.
const v = {
a: 1,
b: 2
}
Object.keys(v).reduce((accumulator, current) => {
accumulator.push(v[current]);
return accumulator;
}, []);
我有错误:
元素隐式有一个'any'类型,因为类型'{ a: number;b:数量;}' 没有索引签名.
Element implicitly has an 'any' type because type '{ a: number; b: number; }' has no index signature.
带有 strict: true
的 TypeScript 3.1.操场:此处,请勾选Options
中的所有复选框以激活strict: true代码>.
TypeScript 3.1 with strict: true
. Playground: here, please check all checkboxes in Options
to activate strict: true
.
推荐答案
Object.keys
返回一个 string[]
.这是设计使然,如本问题
Object.keys
returns a string[]
. This is by design as described in this issue
这是故意的.TS 中的类型是开放式的.因此,keysof 可能会少于您在运行时获得的所有属性.
This is intentional. Types in TS are open ended. So keysof will likely be less than all properties you would get at runtime.
有几种解决方案,最简单的一种就是使用类型断言:
There are several solution, the simplest one is to just use a type assertion:
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
创建别名,以返回您想要的类型:
You can also create an alias for keys
in Object
that will return the type you want:
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])[]);
这篇关于打字稿:Object.keys 返回字符串[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!