下面的代碼輸出[ 5142, 5143 ],但我any用作型別。
let a = [{ _id: 5142 }, { _id: 5143 }];
a = a.map((e: any) => {
return e._id;
});
console.log(a);
查看型別,我認為正確的型別是
a = a.map((e: { _id: number }) => {
但它失敗了。
我使用 VSCode。它可以告訴我正確的型別嗎?還是有什么巧妙的console.log(typeof)技巧?
uj5u.com熱心網友回復:
從根本上說,將結果分配map給其他東西,而不是分配給a,因為如果你分配回athena必須被定義為number[] | { _id: number; }[](因為它開始是{ _id: number; }[],然后你試圖把它變成number[])。
如果你將它分配給其他東西,那么你根本不需要指定任何型別,TypeScript 會正確推斷它們:
const a = [{ _id: 5142 }, { _id: 5143 }];
const b = a.map((e) => {
return e._id;
});
console.log(b);
游樂場鏈接
可以重復使用,a但不清楚你為什么要這樣做。這就是它的樣子,但我不推薦它:
let a: number[] | { _id: number; }[] = [{ _id: 5142 }, { _id: 5143 }];
a = a.map((e) => {
return e._id;
});
console.log(a);
游樂場鏈接
TypeScript 的流程分析讓它看到呼叫map,a是 a { _id: number; }[],所以我們不需要型別保護。如果從背景關系中看不出來,你會:
function example(a: number[] | { _id: number; }[]) {
a = a.map((e) => {
return typeof e === "object" ? e._id : e; // Note the type guard
});
return a;
}
console.log(example([{ _id: 5142 }, { _id: 5143 }]));
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533288.html
標籤:节点.js打字稿
上一篇:更改HookonClick中的值
