在TypeScript中,为什么我的字符串文字不受尊重
我有以下代码:在TypeScript中,为什么我的字符串文字不受尊重,typescript,Typescript,我有以下代码: type Period = "day" | "month" | "year"; let myPeriod: Period = "day"; const anyValue: any = {period: "wrong"}; myPeriod = anyValue.period; console.log(myPeriod); 我希望myPeriod只包含day、month或year的值 但是控制台打印出的错误 如何在myPeriod可能不是day、month或'year'的任
type Period = "day" | "month" | "year";
let myPeriod: Period = "day";
const anyValue: any = {period: "wrong"};
myPeriod = anyValue.period;
console.log(myPeriod);
我希望myPeriod
只包含day
、month
或year
的值
但是控制台打印出的错误
如何在myPeriod
可能不是day
、month
或'year'的任何时间修改代码以返回编译时错误
(如果我尝试类似于
let myPeriod:Period=“error”
,它会在编译时捕获错误)如果您将某个内容键入为any
,根据定义,它将可分配给任何其他类型。还允许访问任何属性,访问的属性类型将为any
一般规则是避免any
,如果您确实有一种未知类型,请使用限制性更强的unknown
(请参阅unknown
与any
)
但在您的情况下,只需删除任何:
type Period = "day" | "month" | "year";
let myPeriod: Period = "day";
const anyValue= {period: "wrong"};
myPeriod = anyValue.period; //error now
console.log(myPeriod);
不要使用any
。使用ENUM可能更适合您的情况。