typescript - 在打字稿中使用 as 关键字
问题描述
在一个对象中,开发人员定义了如下代码常量:
medium: {
fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
fontWeight: '500' as '500',
},
as 关键字在做什么?
解决方案
在这种情况下所做的是as '500'
将 fontWeight 设置为无法通过将 fontWeight 属性设置为 type'500'
而不是string
没有该行的 type 来更改。
例如,在这个Typescript Playground链接中,您会注意到noWork
在为 fontWeight 分配新值时出现类型错误,而works
允许它。
我还添加了一个moreOptions
带有字符串文字类型联合的示例。由于 fontWeights 通常仅适用于特定值,因此对于防止分配无效值的联合来说,这是一个很好的案例。
const noWork = {
fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
fontWeight: '500' as '500',
}
noWork.fontWeight='599' // Type '"599"' is not assignable to type '"500"'.
const works = {
fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
fontWeight: '500',
}
works.fontWeight='599'
const moreOptions = {
fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
fontWeight: '500' as '500'|'600'|'700',
}
moreOptions.fontWeight='600'
moreOptions.fontWeight='425' // Type '"425"' is not assignable to type '"500" | "600" | "700"'.
限制变量允许的类型是打字稿中非常有用的部分,尤其是当某些值适用于属性时。
推荐阅读
- javascript - 使用 setTimeout ( ReactJs) 在一段时间后渲染一个组件
- configuration - 创建 React App Rewired 应用程序忽略 jest.config.js
- xamarin.android - 带有远程 url 的 AnimatedImageDrawable
- java - 如何使用 java.class 中的窗口管理器参数使 Fultter(材料按钮)覆盖显示在顶部?
- azure - 使用 Terraform 创建 Azure IaaS 域控制器
- c++ - 将扫描线写入文件c ++时出现libjpeg-turbo分段错误
- sql - 我需要显示代理主管的薪水
- c# - LINQ 按同一列连接多个表
- reactjs - CRUD API React - 方法不允许 405
- scala - 如何从 Mill build.sc 文件中的 Seq[Path] 创建源?