使用typescript中的变量访问对象键

And*_*wak 4 typescript

在typescript中,如何使用变量访问对象键(属性)?

例如:

interface Obj {
    a: Function;
    b: string;
}

let obj: Obj = {
    a: function() { return 'aaa'; },
    b: 'bbbb'
}

for(let key in obj) {
    console.log(obj[key]);
}
Run Code Online (Sandbox Code Playgroud)

但是typescript抛出以下错误信息:

'TS7017元素隐式具有'任意'类型,因为类型'obj'没有索引签名'

怎么解决?

art*_*tem 6

要编译此代码--noImplicitAny,您需要使用某种类型检查的Object.keys(obj)函数版本,在某种意义上进行类型检查,以便只返回在其中定义的属性的名称obj.

TypeScript AFAIK中没有内置的此类功能,但您可以提供自己的功能:

interface Obj {
    a: Function;
    b: string;
}

let obj: Obj = {
    a: function() { return 'aaa'; },
    b: 'bbbb'
};


function typedKeys<T>(o: T): (keyof T)[] {
    // type cast should be safe because that's what really Object.keys() does
    return Object.keys(o) as (keyof T)[];
}


// type-checked dynamic property access
typedKeys(obj).forEach(k => console.log(obj[k]));

// verify that it's indeed typechecked
typedKeys(obj).forEach(k => {
    let a: string = obj[k]; //  error TS2322: Type 'string | Function' 
                           // is not assignable to type 'string'.
                          //  Type 'Function' is not assignable to type 'string'.
});
Run Code Online (Sandbox Code Playgroud)

  • 这太复杂了。这将是反对 TS 的一个论点。如果没有更简单的解决方案,我会的。 (2认同)

小智 6

I found using keyOf to be the easiest solution

const logKey = (key: keyof Obj) => {
    console.log(obj[key])
}

for(let key in obj) {
    logKey(key)
}
Run Code Online (Sandbox Code Playgroud)


小智 5

你也可以做这样的事情:

const keyTyped = key as keyof typeof Obj;
const value = Obj[keyTyped];
Run Code Online (Sandbox Code Playgroud)