了解 TypeScript 类型系统:生成数组和常量断言的问题

问题描述 投票:0回答:1

我相信我面临着对 TypeScript 的基本理解问题,如以下代码片段中的行为所证明的那样。我试图理解为什么生成的数组不起作用以及是否有办法解决这个问题。

打字稿

const mySlugs = ['post1', 'post2'] as const // working
const mySlugs = (allPosts.map(post => post._raw.sourceFileName)) as const  // not working
export type SlugType = (typeof mySlugs)[number]

第一行 (const mySlugs = ['post1', 'post2'] as const;) 按预期工作,但第二行 (const mySlugs = (allPosts.map(post => post._raw.sourceFileName)) as const ;) 不(“const”断言只能应用于对枚举成员、字符串、数字、布尔值、数组或对象文字的引用。ts(1355))。

我对 TypeScript 的类型系统或 const 断言有什么误解吗?任何见解或建议将不胜感激!

arrays typescript type-inference
1个回答
0
投票

as const
断言只能用于简单的文字,而不是一般的表达式。来自添加它的版本的文档

注意事项

需要注意的一件事是 const 断言只能立即应用于简单的文字表达式。

错误消息也是这样说的:

“const”断言只能应用于对枚举成员、字符串、数字、布尔值、数组或对象文字的引用。 (1355)

如果您想让生成的数组只读,您可以使用

ReadOnlyArray
实用程序类型:

const mySlugs = allPosts.map(post => post._raw.sourceFileName) as ReadonlyArray<string>;

但这仅能实现

as const
在字面上所做的三件事之一。不过,结果将是一个
string
数组,而不是包含字符串文字类型的元组。

© www.soinside.com 2019 - 2024. All rights reserved.