TypeScript遍历对象属性问题

一、问题 

 比如下面的代码:

type Animal = {
    name: string;
    age: number
}

const animal:Animal={
    name:"dog",
    age:12
}

function test(obj:Animal) {
    for (let k in obj) {
        console.log(obj[k])。//这里出错
    }
}
test(animal)

  报错:

二、解决办法 

1. 把对象声明as any

function test(obj:Animal) {
    for (let k in obj) {
        console.log((obj as any)[k]) //不报错
    }
}

  这个方法直接绕过了typescript的校验机制

2. 给对象声明一个接口

type Animal = {
    name: string;
    age: number;
    [key: string]: any
}

const animal:Animal={
    name:"dog",
    age:12
}

function test(obj:Animal) {
    for (let k in obj) {
        console.log(obj [k]) //不报错
    }
}
test(animal)

  这个可以针对比较常见的对象类型,特别是一些工具方法。

3. 使用泛型 

function test<T extends object>(obj:T) {
    for (let k in obj) {
        console.log(obj [k]) //不报错
    }
}

4. 使用keyof

function test(obj:Animal) {
    let k: (keyof Animal);
    for (k in obj) {
        console.log(obj [k]) //不报错
    }
}
原文地址:https://www.cnblogs.com/gg-qq/p/15508536.html