在一个对象中,开发人员定义了如下代码常量:
medium: {
fontFamily: 'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
fontWeight: '500' as '500',
},
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"'.
限制变量允许的类型是打字稿中非常有用的部分,尤其是当某些值适用于属性时。
在这种情况下,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 有一种叫做字符串文字类型的东西,它允许你定义一个变量允许使用的字符串集。但是,在这种情况下使用它们是没有意义的,因为'500'
显然已经是 type '500'
。