首页 > 解决方案 > 如何从打字稿中的联合接口访问密钥

问题描述

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

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,它说没有keyAinDataB和 no keyBinDataA

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)

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

标签: typescript

解决方案


我自己找到了答案。

通过使用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
}

推荐阅读