0

I have the following code:

type Period = "day" | "month" | "year";

let myPeriod: Period = "day";

const anyValue: any = {period: "wrong"};
myPeriod = anyValue.period;

console.log(myPeriod);

I want myPeriod to have only the values day, month, or year.

But the console prints out wrong.

How can I modify my code to return a compile time error any time myPeriod might not be one of day, month, or `year'?

(If I try something like let myPeriod: Period = "wrong", it does catch the error at compile time)

Mary
  • 1,005
  • 2
  • 18
  • 37

1 Answers1

1

If you type something as any it will by definition be assignable to any other type. Also accessing any property is allowed and the type of the accessed property will be any.

The general rule is to avoid any, if you truly have a type that is not known use the more restrictive unknown (see here for unknown vs any)

In your case though just remove the any:

type Period = "day" | "month" | "year";

let myPeriod: Period = "day";

const anyValue= {period: "wrong"};
myPeriod = anyValue.period; //error now

console.log(myPeriod);
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357