如何根据准确的函数参数值推断类型?

huangapple go评论60阅读模式
英文:

how to infer types based on exact function parameter value?

问题

我有一个函数用于流式传输一些数据

function stream(variable: SomeEnum, callback: (message: Type) => void) {}

TypeScript 如何根据变量来确定 message 的类型?

我有一些情况下,一个流可能会返回多种类型的数据。是否更好的做法是为这种情况使用两个不同的回调函数?

function stream(variable: SomeEnum, callback: (message: Type1 | Type2) => void) {}

泛型或重载能解决这个问题吗?

英文:

I have a function that streams some data

function stream(variable:SomeEnum, callback:(message:Type) => void){}

How can typescript know to type of message based on variable?

I have cases where one stream may also return multiple types? Is it a better practice to have two different callbacks for such case?

function stream(variable:SomeEnum, callback:(message:Type1|Type2) => void){}

Can generics or overloads solve this?

答案1

得分: 2

你正在寻找 TypeScript 的泛型。基本上,你会有一个泛型参数,它受限于扩展 SomeEnum。此外,你将需要一些键值类型,其中键是 SomeEnum 的成员,值是给定 SomeEnum 成员的消息的相应类型:

enum SomeEnum {
  value1,
  value2,
  value3,
}

type EnumMessageMap = {
  [SomeEnum.value1]: 'a' | 'b';
  [SomeEnum.value2]: number;
  [SomeEnum.value3]: boolean;
};

用法示例:

function stream<T extends SomeEnum>(
  variable: T,
  callback: (message: EnumMessageMap[T]) => void,
) {}

stream(SomeEnum.value1, (message: 'a' | 'b') => {});

在线示例

英文:

You are looking for typescript generics. Basically, you will have a generic parameter that is constrained to extend SomeEnum.
Additionally, you will need some key-value type where the keys are the members of SomeEnum and values are the respective types of the message for the given member of SomeEnum:

enum SomeEnum {
  value1,
  value2,
  value3,
}

type EnumMessageMap = {
  [SomeEnum.value1]: &#39;a&#39; | &#39;b&#39;;
  [SomeEnum.value2]: number;
  [SomeEnum.value3]: boolean;
};

Usage:

function stream&lt;T extends SomeEnum&gt;(
  variable: T,
  callback: (message: EnumMessageMap[T]) =&gt; void,
) {}

stream(SomeEnum.value1, (message:&#39;a&#39; | &#39;b&#39;) =&gt; {});

playground

huangapple
  • 本文由 发表于 2023年6月22日 03:40:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定