英文:
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]: 'a' | 'b';
[SomeEnum.value2]: number;
[SomeEnum.value3]: boolean;
};
Usage:
function stream<T extends SomeEnum>(
variable: T,
callback: (message: EnumMessageMap[T]) => void,
) {}
stream(SomeEnum.value1, (message:'a' | 'b') => {});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论