因此,基本上,如果我使用is文本或isNumber字符串之一调用测试,它将决定接受什么类型.

type EvtType = 'isText' | 'isNumber';
function test(firstParam: EvtType , secondParameter: /*firstParam ===isText ? string : number*/)
{
  //...
}

test('isText',2)// error
test('isText', "hey")// works

推荐答案

有多种方法.一般来说,函数的参数类型是静态的,不依赖于任何东西. 如果您希望函数的参数类型相互依赖,则必须使用通用参数、重载参数或go struct 化剩余参数,具体取决于您的用例.从调用者的Angular 来看,它们都表现得相当好,但test()的实现者可能会发现某些方法比其他方法更好.

泛型

您可以将test变成firstParam的类型K中的通用类型,并将secondParameter写成模仿您的伪代码的condtional type:

function test<K extends EvtType>(
    firstParam: K,
    secondParameter: K extends "isText" ? string : number
) {
    //...
}

test('isText', 2)// error
test('isText', "hey")// works

在某些用例中,编译器比条件类型更有机会"理解"的另一种通用方法是创建一个助手接口和look up该接口中的类型:

interface ParamMap {
    isText: string,
    isNumber: number
}
function test<K extends keyof ParamMap>(
    firstParam: K, secondParameter: ParamMap[K]
) {
    //...
}

test('isText', 2)// error
test('isText', "hey")// works

过载

完成此类事情的传统方法是重载,您只需编写单独的调用签名,然后编写实现:

function test(firstParam: "isText", secondParameter: string): void;
function test(firstParam: "isNumber", secondParameter: number): void;
function test(firstParam: "isText" | "isNumber", secondParameter: string | number) {

}
test('isText', 2)// error
test('isText', "hey")// works

struct 化休息参数

最后,您可以使用一个discriminated union(满分tuple types)的go struct 化rest参数,它的行为就像调用者端的过载,但可以在实现中进行缩窄,这与过载不同:

function test(
    ...[firstParam, secondParameter]:
        ["isText", string] |
        ["isNumber", number]
) {
    //...
}

test('isText', 2)// error
test('isText', "hey")// works

Playground link to code

Typescript相关问答推荐

TypScript中的算法运算式

ReturnType此索引方法与点表示法之间的差异

当类型断言函数返回假时,TypScript正在推断从不类型

在类型内部使用泛型类型时,不能使用其他字符串索引

具有继承的基于类的react 组件:呈现不能分配给基类型中的相同属性

使某些(嵌套)属性成为可选属性

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

为什么在这个例子中,我把缺少的属性添加到对象中时,TypeScrip没有拾取,如何修复?

React Typescript项目问题有Redux-Toolkit userSlice角色问题

TypeError:正文不可用-NextJS服务器操作POST

如何在方法中正确地传递来自TypeScrip对象的字段子集?

将带有样式的Reaction组件导入到Pages文件夹时不起作用

如何将类似数组的对象(字符串::匹配结果)转换为类型脚本中的数组?

设置不允许相同类型的多个参数的线性规则

TypeScrip:从嵌套的对象值创建新类型

如何在TypeScrip中使用数组作为字符串的封闭列表?

映射类型不是数组类型

如何使用useSearchParams保持状态

从联合提取可调用密钥时,未知类型没有调用签名

使用 fp-ts 时如何使用 TypeScript 序列化任务执行?