how do I access to the key from union interface in typescript

Viewed 106

I added a package which has type definition like this:

interface DataA {
  keyA: string;
}
interface DataB {
  keyB: string;
}

type Data = DataA | DataB

And I'm trying to make a function which is:

type GetMyKey = (data: Data) => string
const getMyKey: GetMyKey = (data) => data.keyA || data.keyB

And this function makes Typescript Errors, which says that there's no keyA in DataB, and no keyB in DataA

Property 'keyA' does not exist on type 'Data'.
  Property 'keyA' does not exist on type 'DataB'.ts(2339)

Property 'keyB' does not exist on type 'Data'.
  Property 'keyB' does not exist on type 'DataA'.ts(2339)

I think I have to do type narrowing in my function but I don't have any clue how should I do.

1 Answers
Related