TypeScript遍歷對象屬性的問題
更新時間:2021年11月11日 09:48:05 作者:guo&qi
這篇文章主要介紹了TypeScript遍歷對象屬性的問題,文章圍繞TypeScript遍歷對象屬性的相關(guān)資料展開詳細內(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])。//這里出錯
}
}
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]) //不報錯
}
}
到此這篇關(guān)于TypeScript遍歷對象屬性的問題的文章就介紹到這了,更多相關(guān)TypeScript遍歷對象屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript實現(xiàn)一鍵復制內(nèi)容剪貼板
這篇文章主要為大家介紹了JavaScript實現(xiàn)一鍵復制內(nèi)容,document.execCommand原生JS設置剪貼板的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
autojs長寬不定的圖片在正方形圖片居中實現(xiàn)詳解
這篇文章主要為大家介紹了autojs長寬不定的圖片在正方形圖片居中實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01

