首页 > 解决方案 > 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

我错过了关于这些条件的一些东西吗?

标签: typescript

解决方案


由于类型的解析将在运行时发生,因此无法静态确定。

更改代码以在运行时处理这两种情况,如下所示:

const baseOrExtendedFunction = (request: BaseOrExtended) => !isExtended(request) ? baseFunction(request) : extendedFunction(request)

baseOrExtendedFunction(request)

TS游乐场


推荐阅读