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

export const computedType = (item: A|B, key: string | number) => {
  return item[key]
};

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

阅读 4.3k
5 个回答

是要这个效果吗?

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)

既然参数不确定,那就用类型推断

export const computedType = <T extends A | B>(item: T, key: keyof T) => {
  return item[key]
};

TS是没有判断的,但是你的需求是可以实现的。

我的例子:

将传递进来的参数改为对象

type TypeOne = {
    item: A;
    key: string;
}

type TypeTwo = {
    item: B;
    key: number;
}

type Value = TypeOne | TypeTwo;

export const computedType = (value: Value) => {
  return value.item[value.key];
};。
https://stackoverflow.com/que...
interface A {
  name: string;
}

interface B {
  id: number;
}

type ComputedType = {
  (item: A, key: string);
  (item: B, key: number);
}

export const computedType: ComputedType = (item, key) => {
  return item[key]
}

可以用函数重载

export function computedType(item: A, key: string): any;
export function computedType(item: B, key: number): any;
export function computedType(item: A | B, key: string | number): any {
    return item[key];
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题