【问题标题】:Referencing a TypeScript type in Angular 2在 Angular 2 中引用 TypeScript 类型
【发布时间】:2016-10-25 17:43:14
【问题描述】:

这可能是一个基本问题,但也许我对 c# 的了解会误导我。我目前正在尝试在 Typescript 中引用自定义类型,并且仅在我实际提供字符串值而不是类型引用时才允许它。这就是我所拥有的:

export type MyCustomeType=
    'text1' |
    'text2' |
    'text3';

export class MyCustomeTypeUtils {}

在我的组件中,我声明了自定义类型的变量:

var1 : MyCustomeType;

让 var1 获得值的唯一方法是:

var1 = 'text1'

如果我这样做

var1 = MyCustomeType.0

var1 = MyCustomeType.text1

它抛出一个错误,它找不到名称 MyCustomeType。非常感谢任何帮助。

【问题讨论】:

    标签: angular typescript enums


    【解决方案1】:

    这就是它的工作原理。这就是 TypeScript 所说的 String Literal Types

    字符串字面量类型允许您指定字符串必须具有的确切值。在实践中,字符串文字类型与联合类型、类型保护和类型别名很好地结合在一起。您可以结合使用这些功能来获得类似枚举的字符串行为。

    type Easing = "ease-in" | "ease-out" | "ease-in-out";
    class UIElement {
        animate(dx: number, dy: number, easing: Easing) {
            if (easing === "ease-in") {
                // ...
            }
            else if (easing === "ease-out") {
            }
            else if (easing === "ease-in-out") {
            }
            else {
                // error! should not pass null or undefined.
            }
        }
    }
    
    let button = new UIElement();
    button.animate(0, 0, "ease-in");
    button.animate(0, 0, "uneasy"); // error: "uneasy" is not allowed here
    

    您可以传递三个允许的字符串中的任何一个,但任何其他字符串都会给出错误

    '"uneasy"' 类型的参数不能分配给'"ease-in" | "ease-out" | "ease-in-out"' 类型的参数

    注意:如果你想使用真正的枚举TypeScript supports that

    【讨论】:

    • 所以为了给其中一种类型赋值,我必须只给它一个允许的字符串,而不是如何使用枚举?也许我混淆了两者:)
    【解决方案2】:

    我落入了类似的陷阱。你可以做的是在你的 utils 类上创建一个静态返回类型为MyCustomType 的字符串text1

    public static readonly Text1:MyCustomType = 'text1';
    

    那你就可以了

    let myVar:MyCustomType = UtilClass.Text1;
    

    【讨论】:

    • 谢谢丹!但是这种方法对我不起作用:(
    • @eagleEye 抱歉,我戴上了 C# 帽子。我对静态的更改有帮助吗?
    • 嗨丹,抱歉直到现在才看到你的消息,我听说你我一直在混合语言:D。我会尽力让你知道。
    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2016-08-31
    • 2021-12-30
    • 2012-11-26
    • 2016-11-27
    相关资源
    最近更新 更多