Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meaning of this piece of code in typescript? public testOptions: "Undecided" | "Yes" | "No" = "Undecided";

public testOptions: "Undecided" | "Yes" | "No" = "Undecided";
  1. What is meaning of this piece of code in typescript?
  2. What is type of variable testOptions?
  3. Is testOptions an array, string or some thing else?
  4. What does "No" = "Undecided" mean?
  5. What does pipe symbol "|" mean?
like image 903
Shailesh Vikram Singh Avatar asked Dec 08 '22 15:12

Shailesh Vikram Singh


1 Answers

Types that are separated with a pipe symbol | are called union-types and can be read as an OR operation. The = sign in this case denotes an assignment. Meaning property testOptions has the default value "Undecided"

Your code can be rewritten as:

// Foo is of type string, but not just any string, only the literal values
// "Undecided", "Yes", or "No". Any other string won't match the type.
type Foo = "Undecided" | "Yes" | "No";

// Will error because "bar" is not one of "Undecided", "Yes", or "No"
const a: Foo = "bar";

// Will work
const b: Foo = "Undecided";

To learn more about the advanced types in TypeScript, I'd highly recommend the docs on advanced types

like image 62
marvinhagemeister Avatar answered May 15 '23 07:05

marvinhagemeister