@zhouyy
2018-03-16T06:56:23.000000Z
字数 4827
阅读 986
js
//booleanlet isDone: boolean = false;//numberlet decimal: number = 6;let binary: number = 0b1010;//string '';"";``可跨行和嵌套let fullName: string = 'zhou';let fullName: string = "zhou";let fullName: string = `zhou`;let age: number =18;let sentence: string = `Hello, my name is ${ fullName }.I'll be ${age +1} years old next mobth.`;//Array<elemType>let list: number [] = [1,2,3];let list: Array<number> = [1,2,3];//Tuple:和list非常类似,但是tuple一旦初始化,指向不能修改let x: [string, number];x = ["hello",10];//okx[3] = "wold";//outside the set, assigned to 联合类型'string|number'//Enumenum Color {Red, Green, Blue}//默认从0开始let c: Color = Color.Green;enum Color {Red = 1, Green = 2, Blue = 4}//手动改变let c: Color = Color.Green;//Any: any type,opt-out of type-checking 不加入TypeScript的类型检查let list: any[] = [1,true,"free"];list[1]=100;//void 无返回 只能 = undefined or null//undefined or null是其他类型的子集//never 未出现过的数值类型function error(message: string): never {throw new Error(message);}//声明let someValue: any = "this is a thing";let strLenghth: number =(<string>someValue).lenghth;//等价于let strLength: number = (someValue as string).lenghth;
//var (全局)declarations are accessible anywhere within their containing function, module, namespace, or global scopefor (var i = 0; i < 10; i++) {setTimeout(function() { console.log(i); }, 100 * i);}//output:10 10 bcs only i=10 execute set..for (var i = 0; i < 10; i++) {// capture the current state of 'i'// by invoking a function with its current value(function(i) {setTimeout(function() { console.log(i); }, 100 * i);})(i);}//outout 0 1 2 3..(function () {})();//It’s an Immediately-Invoked Function Expression, or IIFE;all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.(https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript)//--var vs let--Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for-loop.Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared.var可多次申明,let不可以重复try {throw "oh no!";}catch (e) {console.log("Oh well.");}// Error: 'e' doesn't exist hereconsole.log(e);//let shadowing the inner loop’s i shadows i from the outer loop.内外层屏蔽 for循环的计数器,就很合适使用let命令function sumMatrix(matrix: number[][]) {let sum = 0;for (let i = 0; i < matrix.length; i++) {var currentRow = matrix[i];for (let i = 0; i < currentRow.length; i++) {sum += currentRow[i];}}return sum;}// the internal state of a const variable is still modifiable.
let [first, ...rest] = [1, 2, 3, 4];console.log(first); // outputs 1console.log(rest); // outputs [ 2, 3, 4 ]//array destructuring, you can have assignment without declaration({ a, b } = { a: "baz", b: 101 });// swap variables[first, second] = [second, first];//remaining items in a list using the syntax ...let [first, ...rest] = [1, 2, 3, 4];console.log(first); // outputs 1console.log(rest); // outputs [ 2, 3, 4 ]//Object destructuringlet 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;//Property renaminglet { a: newName1, b: newName2 } = o;//等价于let newName1 = o.a;let newName2 = o.b;//type specifylet { a, b }: { a: string, b: number } = o;
TypeScript其中一个核心原则,是专注于值的模型(shape)的类型检查。 在TypeScript中接口interfaces的责任就是命名这些类型,而且还是你的代码之间或者是与外部项目代码的契约。
function printLabel(labelledObj: {label: string}) {console.log(labelledObj.label);}var myObj = {size: 10, label: "Size 10 Object"};printLabel(myObj);//改成接口;在这里类型检查系统会检查printLabel这个函数,printLabel函数要求传入一个包含一个label的字符串属性interface labelledvalue{label: string;}function printLabel(labelledObj:lavellvalue){console.log(labelledObj.label);}var myObj = {size: 10, label: "Size 10 Object"};printLabel(myObj);//可选的Properties:有时不是所有定义在interface中的属性都是必须的。例如流行的”option bags”模式(option配置),使用者可以之传入部分定制化属性。如下面“option bags”模式interface SquareConfig { color?: string; width?: number; }function createSquare(config: SquareConfig): {color: string; area: number} {var newSquare = {color: "white", area: 100};if (config.color) {newSquare.color = config.color;}if (config.width) {newSquare.area = config.width * config.width;}return newSquare;}var mySquare = createSquare({color: "black"});//函数类型//下面是定义的interface signature是一个接收两个string的输入参数,并返回boolean的函数类型:interface SearchFunc {(source: string, subString: string): boolean;}var mySearch: SearchFunc;mySearch = function(src: string, sub: string) {var result = src.search(sub);if (result == -1) {return false;}else {return true;}}//数组类型//类似于函数类型,TypeScript也可以描述数组类型。在数组类型中有一个’index’类型其描述数组下标的类型,以及返回值类型描述每项的类型nterface StringArray {[index: number]: string;}var myArray: StringArray;myArray = ["Bob", "Fred"]//Class类型//在C#和java中interface是很常使用的类型系统,其用来强制其实现类符合其契约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 ClockInterface {new (hour: number, minute: number);}//当使用类和接口的时候,我们需要知道类有两种类型:static(静态)部分和instance(实例)部分。如果尝试一个类去实现一个带有构造签名的interface,TypeScript类型检查会提示你错误class Clock implements ClockInterface {currentTime: Date;constructor(h: number, m: number) { }//error}