在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可能更适合您的情况。