欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

TypeScript遍歷對象屬性的問題

 更新時(shí)間:2021年11月11日 09:48:05   作者:guo&qi  
這篇文章主要介紹了TypeScript遍歷對象屬性的問題,文章圍繞TypeScript遍歷對象屬性的相關(guān)資料展開詳細(xì)內(nèi)容,需要的朋友可以參考一下

一、問題 

 比如下面的代碼:

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])。//這里出錯(cuò)
    }
}
test(animal)

報(bào)錯(cuò):

二、解決辦法

1. 把對象聲明as any

function test(obj:Animal) {
    for (let k in obj) {
        console.log((obj as any)[k]) //不報(bào)錯(cuò)
    }
}


  這個(gè)方法直接繞過了typescript的校驗(yàn)機(jī)制

2. 給對象聲明一個(gè)接口

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]) //不報(bào)錯(cuò)
    }
}
test(animal)

  這個(gè)可以針對比較常見的對象類型,特別是一些工具方法。

3. 使用泛型

function test<T extends object>(obj:T) {
    for (let k in obj) {
        console.log(obj [k]) //不報(bào)錯(cuò)
    }
}

4. 使用keyof

function test(obj:Animal) {
    let k: (keyof Animal);
    for (k in obj) {
        console.log(obj [k]) //不報(bào)錯(cuò)
    }
}

到此這篇關(guān)于TypeScript遍歷對象屬性的問題的文章就介紹到這了,更多相關(guān)TypeScript遍歷對象屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論