在打字稿中as关键字的用法

时间:2020-05-24 03:11:10

标签: typescript tsc react-native-paper

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

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

as关键字在做什么?

2 个答案:

答案 0 :(得分:1)

在这种情况下,as '500'所做的工作是通过将{WonderWeight}属性设置为'500'类型而不是string类型,将fontWeight设置为无法更改那条线。

例如,在此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"'.

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

答案 1 :(得分:0)

在这种情况下,as不执行任何操作。

const x = '500';
const y = '500' as '500';
const z = '500' as string;

console.log(x === y);
console.log(z === y);
console.log(x === z);

将输出

true
true
true

我应该添加的注释-TypeScript有一个名为string literal types的东西,它允许您定义允许变量使用的字符串集。但是,在这种情况下使用它们毫无意义,因为'500'显然已经是'500'类型。