基础类型 https://www.tslang.cn/docs/handbook/basic-types.html
布尔值 let isDone : boolean = false ;
数字 let decLiteral : number = 6 ;let hexLiteral : number = 0xf00d ;let binaryLiteral : number = 0b1010 ;let octalLiteral : number = 0o744 ;
字符串 let name : string = "bob" ;let name : string = `Gene` ;let age : number = 37 ;let sentence : string = `Hello, my name is ${name} . I'll be ${age + 1 } years old next month.` ;
数组 let list : number [] = [1 , 2 , 3 ];let list : Array <number > = [1 , 2 , 3 ];
元组 Tuple 元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。 比如,你可以定义一对值分别为 string
和number
类型的元组。
let x : [string , number ];x = ["hello" , 10 ]; x = [10 , "hello" ];
console .log (x[0 ].substr (1 )); console .log (x[1 ].substr (1 ));
x[3 ] = "world" ; console .log (x[5 ].toString ()); x[6 ] = true ;
枚举 enum Color { Red , Green , Blue , } let c : Color = Color .Green ;
enum Color { Red = 1 , Green , Blue , } let c : Color = Color .Green ;console .log (colorName);
enum Color { Red = 1 , Green = 2 , Blue = 4 , } let c : Color = Color .Green ;
Any let notSure : any = 4 ;notSure = "maybe a string instead" ; notSure = false ;
let notSure : any = 4 ;notSure.ifItExists (); notSure.toFixed (); let prettySure : Object = 4 ;prettySure.toFixed ();
let list : any [] = [1 , true , "free" ];list[1 ] = 100 ;
Void function warnUser ( ): void { console .log ("This is my warning message" ); }
let unusable : void = undefined ;
Null 和 Undefined let u : undefined = undefined ;let n : null = null ;
Never function error (message: string ): never { throw new Error (message); } function fail ( ) { return error ("Something failed" ); } function infiniteLoop ( ): never { while (true ) {} }
Object declare function create (o: object | null ): void ;create ({ prop : 0 }); create (null ); create (42 ); create ("string" ); create (false ); create (undefined );
类型断言 let someValue : any = "this is a string" ;let strLength : number = (<string >someValue).length ;
let someValue : any = "this is a string" ;let strLength : number = (someValue as string ).length ;
变量声明 https://www.tslang.cn/docs/handbook/variable-declarations.html
var a = 10 ;let hello = "Hello!" ;const numLivesForCat = 9 ;
解构 解构数组 let input = [1 , 2 ];let [first, second] = input;console .log (first); console .log (second);
[first, second] = [second, first];
function f ([first, second]: [number , number ] ) { console .log (first); console .log (second); } f (input);
let [first, ...rest] = [1 , 2 , 3 , 4 ];console .log (first); console .log (rest);
let [first] = [1 , 2 , 3 , 4 ];console .log (first);
let [, second, , fourth] = [1 , 2 , 3 , 4 ];
对象解构 let o = { a : "foo" , b : 12 , c : "bar" , }; let { a, b } = o;
({ a, b } = { a : "baz" , b : 101 });
let { a, ...passthrough } = o;let total = passthrough.b + passthrough.c .length ;
属性重命名 let { a : newName1, b : newName2 } = o;let newName1 = o.a ;let newName2 = o.b ;
let { a, b }: { a : string ; b : number } = o;
默认值 function keepWholeObject (wholeObject: { a: string ; b?: number } ) { let { a, b = 1001 } = wholeObject; }
函数声明 type C = { a : string ; b?: number };function f ({ a, b }: C ): void { }
function f ({ a = "" , b = 0 } = {} ): void { } f ();
function f ({ a, b = 0 } = { a: "" } ): void { } f ({ a : "yes" }); f (); f ({});
展开 let first = [1 , 2 ];let second = [3 , 4 ];let bothPlus = [0 , ...first, ...second, 5 ];
let defaults = { food : "spicy" , price : "$$" , ambiance : "noisy" };let search = { ...defaults, food : "rich" };
let defaults = { food : "spicy" , price : "$$" , ambiance : "noisy" };let search = { food : "rich" , ...defaults };
对象展开还有其它一些意想不到的限制。 首先,它仅包含对象 自身的可枚举属性 。 大体上是说当你展开一个对象实例时,你会丢失其方法:class C { p = 12 ; m ( ) {} } let c = new C ();let clone = { ...c };clone.p ; clone.m ();
接口 https://www.tslang.cn/docs/handbook/interfaces.html
TypeScript的核心原则之一是对值所具有的结构 进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。function printLabel (labelledObj: { label: string } ) { console .log (labelledObj.label ); } let myObj = { size : 10 , label : "Size 10 Object" };printLabel (myObj);
变形interface LabelledValue { label : string ; } function printLabel (labelledObj: LabelledValue ) { console .log (labelledObj.label ); } let myObj = { size : 10 , label : "Size 10 Object" };printLabel (myObj);
可选属性 interface SquareConfig { color?: string ; width?: number ; } function createSquare (config: SquareConfig ): { color : string ; area : number } { let newSquare = { color : "white" , area : 100 }; if (config.clor ) { newSquare.color = config.clor ; } if (config.width ) { newSquare.area = config.width * config.width ; } return newSquare; } let mySquare = createSquare ({ color : "black" });
只读属性 interface Point { readonly x : number ; readonly y : number ; }
let a : number [] = [1 , 2 , 3 , 4 ];let ro : ReadonlyArray <number > = a;ro[0 ] = 12 ; ro.push (5 ); ro.length = 100 ; a = ro; a = ro as number [];
额外的属性检查 函数类型 interface SearchFunc { (source : string , subString : string ): boolean ; } let mySearch : SearchFunc ;mySearch = function (src: string , sub: string ): boolean { let result = src.search (sub); return result > -1 ; };
可索引的类型 class Animal { name : string ; } class Dog extends Animal { breed : string ; } interface NotOkay { [x : number ]: Animal ; [x : string ]: Dog ; }
interface ReadonlyStringArray { readonly [index : number ]: string ; } let myArray : ReadonlyStringArray = ["Alice" , "Bob" ];myArray[2 ] = "Mallory" ;
类类型 实现接口 interface ClockInterface { currentTime : Date ; setTime (d : Date ); } class Clock implements ClockInterface { currentTime : Date ; setTime (d: Date ) { this .currentTime = d; } constructor (h: number , m: number ) {} }
类静态部分与实例部分的区别 interface ClockConstructor { new (hour : number , minute : number ): ClockInterface ; } interface ClockInterface { tick (); } function createClock ( ctor: ClockConstructor, hour: number , minute: number , ): ClockInterface { return new ctor (hour, minute); } class DigitalClock implements ClockInterface { constructor (h: number , m: number ) {} tick ( ) { console .log ("beep beep" ); } } class AnalogClock implements ClockInterface { constructor (h: number , m: number ) {} tick ( ) { console .log ("tick tock" ); } } let digital = createClock (DigitalClock , 12 , 17 );let analog = createClock (AnalogClock , 7 , 32 );
继承接口 interface Shape { color : string ; } interface PenStroke { penWidth : number ; } interface Square extends Shape , PenStroke { sideLength : number ; } let square = <Square >{};square.color = "blue" ; square.sideLength = 10 ; square.penWidth = 5.0 ;
混合类型 interface Counter { (start : number ): string ; interval : number ; reset (): void ; } function getCounter ( ): Counter { let counter = <Counter >function (start: number ) {}; counter.interval = 123 ; counter.reset = function ( ) {}; return counter; } let c = getCounter ();c (10 );c.reset (); c.interval = 5.0 ;
接口继承类 当接口继承了一个类类型时,它会继承类的成员但不包括其实现。 接口同样会继承到类的private和protected成员。 这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)。 class Control { private state : any ; } interface SelectableControl extends Control { select (): void ; } class Button extends Control implements SelectableControl { select ( ) {} } class TextBox extends Control { select ( ) {} } class Image implements SelectableControl { select ( ) {} } class Location {}
类 作用域关键字
public 无限制访问(默认) private 仅在本类中访问 protected 在派生类中仍然可以访问 abstract class Department { constructor (public name: string ) {} printName (): void { console .log ("Department name: " + this .name ); } abstract printMeeting (): void ; } class AccountingDepartment extends Department { static test = "test" ; private _departmentName : string ; protected readonly departmentLogo : string = "★" ; constructor ( ) { super ("Accounting and Auditing" ); } constructor (private readonly test2: string ) { super ("Accounting and Auditing" ); } get departmentName (): string { return this ._departmentName ; } set departmentName (newName: string ) { this ._departmentName = newName; } printMeeting (): void { console .log ("The Accounting Department meets each Monday at 10am." ); } generateReports (): void { console .log ("Generating accounting reports..." ); } } let department : Department ; department = new Department (); department = new AccountingDepartment (); department.printName (); department.printMeeting (); department.generateReports ();