简体   繁体   English

Generice类型断言(TypeScript高级)

[英]Generice Type assertion (TypeScript Advanced)

Is there a way to choose generic T or K based on the value of error? 有没有一种方法可以根据错误值选择通用T或K?

interface ReduxAction<T = undefined, K = undefined, M = undefined>{
type: string;
payload?: T | K;
meta: M
error?: boolean;
}

You can't, because the value of error is discovered in the execution phase, when typescript is already transpiled to javascript. 您不能,因为将Typescript已经转换为javascript时,会在执行阶段发现错误的值。 In the fact that generics are a typescript feature and not present in the transpiled javascript output, it won't be possible to choose from one or the other while executing the javascript. 实际上,泛型是一种打字稿功能,并且不存在于已转换的javascript输出中,因此在执行javascript时将无法从一个或另一个中进行选择。

You can try to extends this interface and create two different interfaces, one for error and one for w/e your goal is. 您可以尝试扩展此接口并创建两个不同的接口,一个用于错误,一个用于您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM