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
inDataB
和 no keyB
inDataA
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
}
推荐阅读
- html - 我怎样才能使我的 td 和 th 具有相同的宽度 - 包括仅放在 tbody 上的滚动条?
- android - Flutter:任务':cloud_firestore:extractDebugAnnotations'的执行失败
- swift - 球形 UICollectionView
- r - 如果它们具有相同的列,则合并 tibble 表的列表
- angularjs - 如何在打字稿中触发离子后退按钮
- javascript - 使用 AvField[type=date] 将时间戳解析为日期
- ios - uinavigationbar ios中标题的上边距问题
- bluetooth - 蓝牙广告数据
- javascript - 禁用JavaScript时的CSS媒体查询?
- r - `use_import_from' 不是从 'namespace:usethis` 导出的对象