Home > Blockchain >  typescript mapping type does not fit
typescript mapping type does not fit

Time:08-17

type A = { a: number, b: null } | { a: null, b: number };

const aaa: A[] = [{ a: 1, b: null }, { a: null, b: 1 }];


function ccc(props: A) {

}

aaa.map(temp => {
    ccc({ a: temp.a, b: temp.b }) // it comes error
})

https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDeUCGAuKA7ArgWwCMIAnAGigM1wBtqoBfKAH2TSp1vMu3yOIYDcAKCEBjAPZYAzsDSoMsANoBdBFEUoFARi7taDcpr3VdULQ2XCRAMxxZRwAJaSootwAowxcWCmYYAJTIIvQi8qgAdHioYO7AEHhgCAB8wVDprh5GUPGJEaimuWARBAwBQvQBQA

How can I using like this situation?

CodePudding user response:

Passing the original object to ccc works, as does spreading it into a new object.

ccc(temp)
ccc({ ...temp })

CodePudding user response:

Using Unions Types properly can rectify this error, change your type A

from

type A = { a: number, b: null } | { a: null, b: number };

to

type A = { a: number | null, b: null | number };

type A = { a: number | null, b: null | number };

const aaa: A[] = [{ a: 1, b: null }, { a: null, b: 1 }];

function ccc(props: A) {

}

aaa.map(temp => {
    ccc({ a: temp.a, b: temp.b })
})
  • Related