【发布时间】:2019-12-18 05:44:49
【问题描述】:
我正在尝试创建一个只能接受一组已定义键的对象类型。在下面的示例中,'1.1.1' | '1.1.2' | '1.1.3'。
假设levelNum, subLevelNum and problemNum 是集合中的有效字符串。
type AllowedIndexes = '1.1.1' | '1.1.2' | '1.1.3';
type ProblemType = { [index in AllowedIndexes]?: Problem };
let problems: ProblemType = {};
// --> the following line gives the error <--
// `TS2322: Type 'string' is not assignable to type AllowedIndex.`
let ix:AllowedIndexes = `${levelNum}.${subLevelNum}.${problemNum}`;
problems[ix] = new Problem(....)
但是,如果我将错误的行写成如下,它可以工作:
let ix:AllowedIndexes = `${levelNum}.${subLevelNum}.${problemNum}` as AllowedIndexes;
我是在走正确的路,还是完全不去确保对象键属于定义的集合?
【问题讨论】:
标签: typescript