【问题标题】:Parameter of union type of enums?枚举联合类型的参数?
【发布时间】:2018-06-07 07:44:04
【问题描述】:

我有两个枚举

enum Fruit { Apples, Oranges };
enum Vegetable { Garlic, Cucumber };

和类型

type Food = Fruit | Vegetable;

现在我想制作另一种类型,它是一个函数,并以食物为参数

type OnViewFood = (food: Food) => void;

但是当我这样做时

viewFruit: OnViewFood = (fruit: Fruit) => `This is ${fruit}`;

我收到一个错误,即 Food 不能分配给 Fruit。 如何实现我的目标?

【问题讨论】:

    标签: typescript react-native enums union


    【解决方案1】:

    编译器不希望你这样做的原因是它本质上是不安全的。考虑这个例子是否有效:

    let viewFruit: OnViewFood = (fruit: Fruit) => `This is ${fruit}`; // we assign a function that can only handle Fruit.
    
    viewFruit(Vegetable.Cucumber); // the declared signature allows us to use a Vegetable, possibly causing an error 
    

    您可以将OnViewFood 声明为函数的联合,但是调用会成为一个问题,因为您不能调用函数的联合并且您不能轻松地进行类型保护:

    type OnViewFood = ((food: Fruit) => void) | ((food: Vegetable) => void);
    let viewFruit: OnViewFood = (fruit: Fruit) => `This is ${fruit}`; // ok now can be either function signature 
    viewFruit(Vegetable.Cucumber); // now an error 
    

    在任何一种情况下,我们都可以使用类型断言来解决类型错误,您可以选择任一选项,具体取决于您更信任哪一方,函数创建方或调用方:

    // Type assertion on call 
    type OnViewFood = ((food: Fruit) => void) | ((food: Vegetable) => void);
    let viewFruit: OnViewFood = (fruit: Fruit) => `This is ${fruit}`;
    
    (viewFruit as any as ((food: Vegetable) => void))(Vegetable.Cucumber);
    
    // Type assertion on declaration 
    type OnViewFood = (food: Food) => void
    let viewFruit: OnViewFood = ((fruit: Fruit) => `This is ${fruit}`) as (food: Food) => void;
    viewFruit(Vegetable.Cucumber);
    

    【讨论】:

    • 使用原始代码时出现错误OnViewFood only refers to a type, but is being used as a value here. 不知道为什么。调用别名类型的函数的推荐方法是什么?
    猜你喜欢
    • 2018-02-14
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多