【问题标题】:TS: How to handle multiple possible types on a single type?TS:如何在一个类型上处理多种可能的类型?
【发布时间】:2020-07-15 20:02:10
【问题描述】:

我有一个模态数据接口

interface ModalData {
 ...
 payload: any; // At any given time, this payload might be a string or number or boolean;
 ...
}

在模态数据payload中可能有不同的类型,为此我创建了另一种类型:

type IPayLoad = string | number | boolean;

现在,当我在我的代码中使用这种类型时,我遇到了以下错误。

问题是我不喜欢将any 类型设置为上面的有效负载。 但如果我将其设置为 IPayLoad 类型,则会出现以下错误。

this.service.saveString(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'string'.

this.service.saveNumber(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'number'.

this.service.saveBool(modal.payload) // Argument of type 'IPayLoad' id not assignable to parameter of type 'boolean'.

服务中的调用函数如下:

public saveString(res: string): void {}

public saveNumber(res: number): void {}

public saveBool(res: boolean): void {}

【问题讨论】:

  • 你怎么知道调用哪个方法?

标签: javascript typescript types interface


【解决方案1】:

假设您已将 ModalData.payload 的类型设置为 IPayLoad 而不是 any,您需要像这样缩小联合类型:

if (typeof modal.payload === 'string') {
    saveString(modal.payload)
} else if (typeof modal.payload === 'number') {
    saveNumber(modal.payload)
} else if (typeof modal.payload === 'boolean') {
    saveBool(modal.payload)
}

typeof-checks 称为类型保护,您可以在TypeScript documentation 中了解更多信息。

【讨论】:

    【解决方案2】:

    我认为您可以使用一种接受IPayloadstring|boolean|number 类型的方法。

    但是如果你真的要使用这三个功能,

    您可以执行以下操作:

    this.service.saveString(`${payload}`);
    
    this.service.saveNumber(Number(payload));
    
    this.service.saveBoolean(Boolean(payload));
    

    【讨论】:

    • 谢谢@bravemaster,但是如果类型变成更复杂的对象而不是上面的预定义类型怎么办?
    • @superbadcodemonkey 有一个更相关的答案。请参考它。但是您需要将所有这些组合到一个接受 IPayload 类型并进行类型检查的函数中。
    【解决方案3】:

    关键字as解决了这里的问题。

    public getLoad (payload: IPayLoad) {
    
      this.service.saveString(payload as string);
    
      this.service.saveNumber(payload as number);
    
      this.service.saveBoolean(payload as boolean);
    
    }
    

    【讨论】:

    • 这在任何方面都不是类型安全的,请不要这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多