typescript - TypeScript 条件类型 - 在所有情况下都返回一种类型
问题描述
在我的项目中,我想根据参数的类型选择将哪个函数应用于参数。所以有一个基本接口和一个扩展接口,它向基本接口添加了一个属性。所以我想检查这个添加的属性是否不是undefined
,并将它传递给具有正确类型的正确函数。所以这是代码(和 )
interface BaseType {
field1: string
field2: string
}
interface ExtendedType extends BaseType {
id: number
}
const values: any = {
id: undefined,
field1: "String",
field2: "Value"
}
const requestObj = {
field1: values['field1'],
field2: values['field2']
}
const request = values['id'] !== undefined ? {...requestObj, id: values['id']}: requestObj
type BaseOrExtended = typeof request extends ExtendedType ? ExtendedType : BaseType;
function baseFunction(request: BaseType) {
console.log('Do BASE action')
}
function extendedFunction(request: ExtendedType) {
console.log('Do Extended action')
}
function isExtended(item: ExtendedType| BaseType): item is ExtendedType {
return (item as ExtendedType).id !== undefined
}
const baseOrExtendedFunction = isExtended(request) ? baseFunction : extendedFunction
baseOrExtendedFunction(request as BaseOrExtended)
但我确实得到了一个错误
“BaseType”类型的参数不能分配给“ExtendedType”类型的参数。“BaseType”类型中缺少属性“id”,但在“ExtendedType”类型中是必需的。
并且不管id
它想要执行的价值是什么extendedFunction
。而且总是type BaseOrExtended = BaseType
我错过了关于这些条件的一些东西吗?
解决方案
由于类型的解析将在运行时发生,因此无法静态确定。
更改代码以在运行时处理这两种情况,如下所示:
const baseOrExtendedFunction = (request: BaseOrExtended) => !isExtended(request) ? baseFunction(request) : extendedFunction(request)
baseOrExtendedFunction(request)
推荐阅读
- html - 用于表格水平滚动的跨浏览器功能
- itext - 如何处理 XMLWorkerHelper.ParseToElementList 中的图像
- uwp - 使用 UWP 地图作为用户旅行位置绘制路线的最佳方法是什么
- react-native - React native:createStackNavigator 与实际屏幕内容重叠(Android)
- ibm-midrange - 在 RPG 中覆盖。
- python-3.x - Mypy 在类型分支时错误地报告联合类型变量的错误
- c# - 在 C# Xamarin.Forms 中将 DatePicker 绑定到类 Model 的字符串属性
- excel - 计算不是 Application 或 ActiveWorkbook 的方法
- git - 仅还原分支上的更改
- java - 具有 Where 约束的 SecondaryTable