将一个类型缩小为.js文件中Typescript的常量



我有一些.js配置文件和一个tsconfig,用于这些带有checkJs: true的文件。库(Terser(的类型为:

ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020

在我的配置文件中,我有ecma: 2017。TS认为其类型为CCD_ 5。在.ts文件中,我只能使用as const。在.js文件中,有什么方法可以让TS将2017缩小为常数吗?

您可以在jsdoc中使用const断言,如本期中所述

// let config: {
//     readonly ecma: "2017";
// }
let config = /** @type {const} */ ({ 
ecma: "2017"
})
// Or 
// let config2: {
//     ecma: "2017";
// }
let config2 = { 
ecma: /** @type {const} */ ("2017")
}

游乐场链接

注意:需要在要创建const的表达式周围使用()

我会在一个组合中做两件事来确保它是一个常数:

首先,确保道具在运行时是不可变的,不管怎样。

///config.js
const config = {
anotherProp: true,
ecma: 2017
};
Object.defineProperty(config, "ecma", { value: 2017, writable: false });
export default config;

第二个创建d.ts文件到";测试";这个道具是只读的

/// config.d.ts
type Config = {
anotherProp: string;
readonly ecma: 2017;
};
declare const conf: Config;
export default conf;

结果是打字脚本会抱怨的变化

//ts error: Cannot assign to 'ecma' because it is a read-only property.ts(2540)
config.ecma = 6;

即使你试图破解它,它也会在运行时失败:

//runtime error: Cannot assign to read only property 'ecma' of object '#<Object>'
(config as any).ecma = 6;

游乐场链接这里:这里

最新更新