const x = [{a: 1, b: 2}].map((d: any) => ({...d, c: 'something new'}))
我怎樣才能使x上面c property的物件陣列具有?
我試過
const x = ([{a: 1, b: 2}] as any).map((d: <{c: string}>) => ({...d, c: 'something new'}))
但它似乎不是正確的語法。
uj5u.com熱心網友回復:
<>指定行內型別時不需要
const x = ([{a: 1, b: 2}] as any).map((d: {c: string}) => ({...d, c: 'something new'}))
你可以像這樣輸入結果
const x: Array<{a:number; b: number; c:string;}> = [{a: 1, b: 2}].map((d) => ({...d, c: 'something new'}))
或者干脆讓 TypeScript 弄清楚(首選 @AluanHaddad 提到的)
const x = [{a: 1, b: 2}].map((d) => ({...d, c: 'something new'}));
uj5u.com熱心網友回復:
有時,命名和注釋您想要弄清楚需要什么的型別會有所幫助。
interface AB {
a: number
b: number
}
interface ABC extends AB {
c: string
}
const x: ABC[] // annotate what's expected
= [{a: 1, b: 2} as AB] // input, array of AB
.map(
ab => // allow inference to type ab as AB
({...ab, c: 'something new'}) // result is shape of ABC (per element)
)
// Once more, allowing type inference to do the work
// just to show we can be succinct when we want to be
const y = [{ a: 1, b: 2 }].map(ab => ({...ab, c: 'something'}))
// ^ NB: y is not typed as ABC[], but has the right shape
const x: ABC[] ...就我個人而言,我經常喜歡在接收變數(很難摸索)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468530.html
標籤:javascript 打字稿
