求助:关于 includes 与类型收敛的问题

17 阅读1分钟

我的本意是通过 includes 来收敛类型,使得 string > ApiParams['object_type'],但是很明显对于 ts,includes 是不接收这种写法的,它会毫不客气的丢给你一个 ERROR

“什么东西就敢放进来判断在不在,我直接红色波浪线!” —— includes

那么,怎么才能优雅的 使得 string > ApiParams['object_type'] 呢?

除了在 includes 使用 as 断言以及后续继续 as 断言,还有更好的解法吗?

代码如下:

// 模拟的 API 参数类型
type ApiParams = {
  object_type: 'apple' | 'banana' | 'orange' | 'grape';
};

// 当前的写法 - 会报 TS 错误
const VALID_TYPES: ApiParams['object_type'][] = ['apple', 'banana', 'orange', 'grape'];

function processItem(itemType: string) {
  // ❌ TS 错误:Argument of type 'string' is not assignable to parameter of type '"apple" | "banana" | "orange" | "grape"'
  if (VALID_TYPES.includes(itemType)) {
    // ❌ TS 错误:Type 'string' is not assignable to type '"apple" | "banana" | "orange" | "grape"'
    const params: ApiParams = { object_type: itemType };
  }
}