Typescript:基于泛型进行推断

标签 typescript generics type-inference

当为 arg1 放置类型保护时,我希望自动推断出 arg2,但事实并非如此。

有人知道为什么这不起作用吗?最好的选择是什么?非常感谢!

您可以看到正在运行的类型 here 。只需将鼠标悬停在 arg2 上即可查看推断的类型。

function example<T extends 'foo' | 'bar'>(
  arg1: T, 
  arg2: T extends 'foo' ? string : number
) {
  if (arg1 === 'foo') {
    arg2 // should be string?
  }

  if (arg1 === 'bar') {
    arg2 // should be number?
  }
}

但是,调用该函数确实正确应用了第二个参数类型:

enter image description here

enter image description here

这是使用基于泛型的类型化对象的另一个示例:

type Test <T extends boolean> = {
  multiple: T;
  value: T extends true ? string : number;
};

// this doesn't work?
function test <T extends boolean>(a: Test<T>) {
  if (a.multiple) {
    a.value // string | number?
  }else{
    a.value // string | number?
  }
}

// this works!
function test2 (a: Test<true> | Test<false>) {
  if (a.multiple) {
    a.value // is string
  }else{
    a.value // is number
  }
}

参见playground

最佳答案

我使用这两种解决方案来获得条件参数:

解决方案 1(推荐):使用对象作为参数

type Args = { arg1: 'foo'; arg2: string } | { arg1: 'bar'; arg2: number };
function example(args: Args): void {
  if (args.arg1 === 'foo') {
    args.arg2; // It's string
  }
  if (args.arg1 === 'bar') {
    args.arg2; // It's number
  }
}

解决方案 2:使用参数对象

type Args = ['foo', string] | ['bar', number];
function example(...args: Args): void {
  if (args[0] === 'foo') {
    args[1]; // It's string
  }
  if (args[0] === 'bar') {
    args[1]; // It's number
  }
}

关于Typescript:基于泛型进行推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65038122/

相关文章:

javascript - 在 Angular 6 的 do while 循环中延迟递归 HTTP get 请求

java - 如何解释这种看似不一致的 Java 可变参数行为?

.net - 是否可以在将自身指定为泛型类型参数的同时发出从泛型类型派生的类型?

c# - 尝试在 C# 中构造泛型类型失败并出现 MissingMethodException

c++ - 由于模板实例化导致的意外类型

javascript - 更改时的 Angular 选择值不更新

Angular getCurrentNavigation().extras

json - Angular 2+ - 将 JSON 解析为数字

haskell - 这个 Haskell 函数的类型签名是什么?

rust - 为什么使用 "Self"作为参数类型会引发生命周期错误?