The primitives: string
, number
, and boolean
string
represents string values like"hello world"
number
is for numbers like32
,no equivalent to int or flaot - everything is simplynumber
.boolean
is for the two valuestrue
,andfalse
.
Arrays
To specify the type of an array like [1,2,3]
use number[]
Type Annotations on Variables 变量的类型注解
1 |
|
Functions
1 |
|
return type
1 |
|
Anonymous Functions匿名函数
1 |
|
Optional Properties
to check Object is possible ‘undefined
1 |
|
Type Aliases
1 |
|
Interfaces
An interface declaration is another way to name an object type:
1 |
|
Literal Types 字面量类型
1 |
|
Narrowing
typeof
- string
- number
- bigint
- boolean
- symbol
- undefined
- object
- function
TypeScript knows that only astring
value will have atypeof
value “string”if you have a union where all the members have something in common. For example, both arrays and strings1
2
3
4
5
6
7function printId(id: number | string) {
if (typeof id === 'string') [
console.log(id.toUpperCase());
] else {
console.log(id);
}
}
1 |
|
instanceof narrowing
1 |
|
Discriminated unions
1 |
|
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
return Math.PI * shape.radius ** 2;
// Property 'radius' does not exist on type 'Shape'
}
function getAreaFix(shape: Shape) {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2; // shape: Circle
}
}
// In this case, kind was that common property. The same checking works with `switch` statements as well.
function getAreaSwitch(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
}
}