string represents string values like "hello world"
number is for numbers like 32,no equivalent to int or flaot - everything is simply number.
boolean is for the two values true,and false.
Arrays
To specify the type of an array like [1,2,3] use number[]
Type Annotations on Variables 变量的类型注解
1 2
letname: string = "Alice"; // In most cases, though, this isn't needed. TS tries to automatically infer the types in your code.
Functions
1 2 3 4 5
functiongreet(name: string) { console.log("Hello" + name.toUpperCase() + "!"); } // error, paramter need a string. greet(34);
return type
1 2 3
functiongetNumber(): number { return32; }
Anonymous Functions匿名函数
1 2 3 4 5 6 7 8
const names = ["Alice", "Bob", "Eve"];
names.forEach(function (s){ // Property 'toUppercase' does not exits on type 'string', Did you mean 'toUpperCase'. console.log(s.toUppercase()); }) // Even though the parameter `s` didn't have a type annotation,TypeScript used the types of the `forEach` function // along with the inferred type of the Array, to determine the type `s` will have.
Optional Properties
to check Object is possible ‘undefined
1 2 3 4 5 6
functionprintName(obj: { first: string, last?: string }) { // Object is possible 'undefined' if (obj.last !== undefined) { console.log(obj.last.toUpperCase()); } }
Type Aliases
1 2 3 4 5 6 7 8
typePoint = { x: number; y: number; }
typeID = number | string;
typeUserInputSanitizedString = string;
Interfaces
An interface declaration is another way to name an object type:
1 2 3 4 5 6 7 8 9 10 11
interfacePoint { x: number; y: number; }
functionprintCoord(pt: Point) { console.log("The coordinate's x value is " + pt.x); console.log("The coordinate's y value is " + pt.y); }
functionhandleShape(shape: Shape) { // oops! if (shape.kind === "rect") { // This condition will always return 'false' since the types '"circle"' | '"square"' and '"rect"' have no overlap. } }
functiongetAreaFix(shape: Shape) { if (shape.kind === 'circle') { // we could try to use a non-null assertion (a `!` after `shape.radius`) to say that `radius` is definitely present. returnMath.PI * shape.radius! ** 2; } }
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;
}
}