blog

首页 / typescript / Think of Types as Sets of Values

Think of Types as Sets of Values (!important)

At runtime, every variable has a single value chosen from JavaScript’s universe of values. There are many possible values, including:

But before your code runs, when TypeScript is checking it for errors, a variable just has a type. This is best thought of as a set of possible values. This set is known as the domain of the type. For instance, you can think of the number type as the set of all number values. 42 and -37.25 are in it, but ‘Canada’ is not. Depending on strict NullChecks, null and undefined may or may not be part of the set.

interface Person {
 name: string;
 age: number;
}
interface Lifespan {
 birth: Date;
 death?: Date;
}
type PersonAndLifespan = Person & Lifespan
type PersonOrLifespan = Person | Lifespan

const ps: PersonAndLifespan = {
 name: 'Alan Turing',
 birth: new Date('1912/06/23'),
 death: new Date('1954/06/07'),
}; // ERROR 'age' is declared here.

const ps: PersonOrLifespan = {
 name: 'Alan Turing',
 birth: new Date('1912/06/23'),
 death: new Date('1954/06/07'),
}; // OK
// Disclaimer: these are relationships, not TypeScript code!
keyof (A&B) = (keyof A) | (keyof B)
keyof (A|B) = (keyof A) & (keyof B)

Things to Remember