如何在typescript中访问union接口中的键?



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

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错误,表示在DataB中没有keyA,在DataA中没有keyB

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)

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

我刚刚自己找到了答案。

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

最新更新