是否有可能有一个具有常量字符串的类,可以在typescript中编译为内联代码?

时间:2022-03-24 13:13:02

What I am looking for is the exact same functionality as a const enum in TypeScript but for strings. It doesn't have to be an actual type (although that would be a bonus), but what I am looking for is a way to have a large list of const strings that get compiled into the JS. The reason is that we have a large list of "magic strings" that I would like to replace with something a bit less error prone, but I don't want the overhead of having a huge list of types that aren't used on every page.

我正在寻找的是与TypeScript中的const enum完全相同的功能,但是对于字符串。它不一定是一个实际的类型(虽然这将是一个额外的奖励),但我正在寻找的是一种方法,有一个很大的const字符串列表,可以编译到JS中。原因是我们有一个很大的“魔术字符串”列表,我想用一些不易出错的东西替换它,但我不希望有一个巨大的类型列表的开销,这些类型并不是每个都没有使用页。

TypeScript:

const enum Foo {
    BarA = "BarA";
    BarB = "BarB";
}

class Test {
    myFunction = () => {
        var a = Foo.BarA;
    }
}

Compiled JavaScript:

var Test = (function () {
    function Test() {
        this.myFunction = function () {
            var a = "BarA";
        };
    }
    return Test;
})();

1 个解决方案

#1


Is it possible to have a class with constant strings that get compiled as inline code in typescript

是否有可能有一个具有常量字符串的类,这些字符串在typescript中被编译为内联代码

Not at the moment.

现在不行。

That said I would just use an object literal and let TypeScript infer the correct type :

那就是说我只使用一个对象文字,让TypeScript推断出正确的类型:

var foo = {
    bar: 'bar',
    bas: 'bas'
}


var something = foo.bar; // Okay 
var somethingElse = foo.baz; // Error

Ofcourse you don't get inlining but you do remove the magic nature of these strings.

当然,你没有内联,但你确实删除了这些字符串的魔力。

#1


Is it possible to have a class with constant strings that get compiled as inline code in typescript

是否有可能有一个具有常量字符串的类,这些字符串在typescript中被编译为内联代码

Not at the moment.

现在不行。

That said I would just use an object literal and let TypeScript infer the correct type :

那就是说我只使用一个对象文字,让TypeScript推断出正确的类型:

var foo = {
    bar: 'bar',
    bas: 'bas'
}


var something = foo.bar; // Okay 
var somethingElse = foo.baz; // Error

Ofcourse you don't get inlining but you do remove the magic nature of these strings.

当然,你没有内联,但你确实删除了这些字符串的魔力。