如何从打字稿中的联合接口访问密钥

时间:2021-03-08 11:19:11

标签: typescript

我添加了一个具有如下类型定义的包:

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

type Data = DataA | DataB

我正在尝试创建一个函数:

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

这个函数会产生 Typescript Errors,它表示 keyA 中没有 DataBkeyB 中没有 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)

我想我必须在我的函数中进行类型缩小,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我自己才找到答案。

使用in关键字

https://stackoverflow.com/a/50214853/6661359

const getMyKey: GetMyKey = (data) => {
  return ('keyA' in data) ? data.keyA : data.keyB
}

通过使用类型谓词(又名类型保护)

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

const isDataA = (data: Data): data is DataA => {
  return (data as DataA).keyA !== undefined
}

const getMyKey: GetMyKey = (data) => {
  return (isDataA(data)) ? data.keyA : data.keyB
}