首页 > 解决方案 > 在打字稿中使用 as 关键字

问题描述

在一个对象中,开发人员定义了如下代码常量:

medium: {
      fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
      fontWeight: '500' as '500',
    },

as 关键字在做什么?

标签: typescripttscreact-native-paper

解决方案


在这种情况下所做的是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"'.

限制变量允许的类型是打字稿中非常有用的部分,尤其是当某些值适用于属性时。


推荐阅读