[英]how do I access to the key from union interface in typescript
I added a package which has type definition like this:我添加了一个 package ,它的类型定义如下:
interface DataA {
keyA: string;
}
interface DataB {
keyB: string;
}
type Data = DataA | DataB
And I'm trying to make a function which is:我正在尝试制作一个 function 这是:
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
而这个 function 使 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)
I think I have to do type narrowing in my function but I don't have any clue how should I do.我想我必须在 function 中进行类型缩小,但我不知道该怎么做。
I just found answer by myself.我自己找到了答案。
in
keywordin
关键字https://stackoverflow.com/a/50214853/6661359 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 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.