限制 TS 传入的多个参数类型必须不同时,该怎么写?

作者站长头像
站长
· 阅读数 14
export const computedType = (item: A|B, key: string | number) => {
  return item[key]
};

我希望当传入的第一个参数类型为A时,第二个参数类型就只能为string,当传入的第一个参数类型为B时,第二个参数类型就只能为number,此处的ts类型该怎么写呢?

回复
1个回答
avatar
test
2024-07-17

是要这个效果吗?answer image

type A = string[]

type B = {
  name: string
}


function demo<T extends A | B> (type: T, value: T extends A ? string : number) {
  return `${type}=>${value}`
}


demo([''], '456')

demo({
  name: ''
}, 123)


// ❌ 错误
demo([''], 4564)
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容