无需const断言将类型收窄为值的穷尽类型联合
问题
我有一段代码,当不对数组subject使用const断言时,推导出来的Subject类型是宽泛的{ field: string },无法精确到数组元素中field的具体值:
/** * 未使用const assertion */ const subject = [ { "field": "string_1", }, { "field": "string_2", }, ]; type Subject = typeof subject[number];
推导结果:
type Subject = { field: string; }
我需要把Subject类型收窄为包含所有field具体值的联合类型——当给数组添加as const断言后,就能得到预期的精确类型:
/** * 使用const assertion */ const subject = [ { "field": "string_1", }, { "field": "string_2", }, ] as const; type Subject = typeof subject[number];
推导结果:
type Subject = { readonly field: "string_1"; } | { readonly field: "string_2"; }
但我的实际场景中,subject是从第三方库导入的,无法直接对它添加as const断言,请问该如何实现上述的类型收窄效果?
尝试方案
我尝试了以下代码,想通过提取字段来生成精确类型:
/** * 未使用const assertion */ const subject = [ { "field": "string_1", }, { "field": "string_2", }, ]; /** * 错误:A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals. */ const subjectConst = subject[number]["field"] as const; type SubjectConst = typeof subjectConst;
但运行时报错:
Error: A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.(1355)
内容的提问来源于stack exchange,提问作者Malix
相关产品推荐
相关产品推荐

