我添加了一个具有如下类型定义的包:
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
中没有 DataB
,keyB
中没有 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)
我想我必须在我的函数中进行类型缩小,但我不知道该怎么做。
答案 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
}