[关闭]
@zhouyy 2018-03-16T06:56:23.000000Z 字数 4827 阅读 986

TypeScript

js


Basic Type

  1. //boolean
  2. let isDone: boolean = false;
  3. //number
  4. let decimal: number = 6;
  5. let binary: number = 0b1010;
  6. //string '';"";``可跨行和嵌套
  7. let fullName: string = 'zhou';
  8. let fullName: string = "zhou";
  9. let fullName: string = `zhou`;
  10. let age: number =18;
  11. let sentence: string = `Hello, my name is ${ fullName }.
  12. I'll be ${age +1} years old next mobth.`;
  13. //Array<elemType>
  14. let list: number [] = [1,2,3];
  15. let list: Array<number> = [1,2,3];
  16. //Tuple:和list非常类似,但是tuple一旦初始化,指向不能修改
  17. let x: [string, number];
  18. x = ["hello",10];//ok
  19. x[3] = "wold";//outside the set, assigned to 联合类型'string|number'
  20. //Enum
  21. enum Color {Red, Green, Blue}//默认从0开始
  22. let c: Color = Color.Green;
  23. enum Color {Red = 1, Green = 2, Blue = 4}//手动改变
  24. let c: Color = Color.Green;
  25. //Any: any type,opt-out of type-checking 不加入TypeScript的类型检查
  26. let list: any[] = [1,true,"free"];
  27. list[1]=100;
  28. //void 无返回 只能 = undefined or null
  29. //undefined or null是其他类型的子集
  30. //never 未出现过的数值类型
  31. function error(message: string): never {
  32. throw new Errormessage);
  33. }
  34. //声明
  35. let someValue: any = "this is a thing";
  36. let strLenghth: number =(<string>someValue).lenghth;
  37. //等价于
  38. let strLength: number = (someValue as string).lenghth;

Variable Declarations

  1. //var (全局)declarations are accessible anywhere within their containing function, module, namespace, or global scope
  2. for (var i = 0; i < 10; i++) {
  3. setTimeout(function() { console.log(i); }, 100 * i);
  4. }//output:10 10 bcs only i=10 execute set..
  5. for (var i = 0; i < 10; i++) {
  6. // capture the current state of 'i'
  7. // by invoking a function with its current value
  8. (function(i) {
  9. setTimeout(function() { console.log(i); }, 100 * i);
  10. })(i);
  11. }//outout 0 1 2 3..
  12. (function () {
  13. })();
  14. //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)
  15. //--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不可以重复
  16. try {
  17. throw "oh no!";
  18. }
  19. catch (e) {
  20. console.log("Oh well.");
  21. }
  22. // Error: 'e' doesn't exist here
  23. console.log(e);
  24. //let shadowing the inner loop’s i shadows i from the outer loop.内外层屏蔽 for循环的计数器,就很合适使用let命令
  25. function sumMatrix(matrix: number[][]) {
  26. let sum = 0;
  27. for (let i = 0; i < matrix.length; i++) {
  28. var currentRow = matrix[i];
  29. for (let i = 0; i < currentRow.length; i++) {
  30. sum += currentRow[i];
  31. }
  32. }
  33. return sum;
  34. }
  35. // the internal state of a const variable is still modifiable.

Destructuring:将数组和对象的属性赋给各种变量

  1. let [first, ...rest] = [1, 2, 3, 4];
  2. console.log(first); // outputs 1
  3. console.log(rest); // outputs [ 2, 3, 4 ]
  4. //array destructuring, you can have assignment without declaration
  5. ({ a, b } = { a: "baz", b: 101 });
  6. // swap variables
  7. [first, second] = [second, first];
  8. //remaining items in a list using the syntax ...
  9. let [first, ...rest] = [1, 2, 3, 4];
  10. console.log(first); // outputs 1
  11. console.log(rest); // outputs [ 2, 3, 4 ]
  12. //Object destructuring
  13. let o = {
  14. a: "foo",
  15. b: 12,
  16. c: "bar"
  17. };
  18. let { a, b } = o;
  19. //改变赋值 注意括号
  20. ({ a, b } = { a: "baz", b: 101 });
  21. //...
  22. let { a, ...passthrough } = o;
  23. let total = passthrough.b + passthrough.c.length;
  24. //Property renaming
  25. let { a: newName1, b: newName2 } = o;
  26. //等价于
  27. let newName1 = o.a;
  28. let newName2 = o.b;
  29. //type specify
  30. let { a, b }: { a: string, b: number } = o;

Interface

TypeScript其中一个核心原则,是专注于值的模型(shape)的类型检查。 在TypeScript中接口interfaces的责任就是命名这些类型,而且还是你的代码之间或者是与外部项目代码的契约。

  1. function printLabel(labelledObj: {label: string}) {
  2. console.log(labelledObj.label);
  3. }
  4. var myObj = {size: 10, label: "Size 10 Object"};
  5. printLabel(myObj);
  6. //改成接口;在这里类型检查系统会检查printLabel这个函数,printLabel函数要求传入一个包含一个label的字符串属性
  7. interface labelledvalue{
  8. label: string;
  9. }
  10. function printLabel(labelledObj:lavellvalue){
  11. console.log(labelledObj.label);
  12. }
  13. var myObj = {size: 10, label: "Size 10 Object"};
  14. printLabel(myObj);
  15. //可选的Properties:有时不是所有定义在interface中的属性都是必须的。例如流行的”option bags”模式(option配置),使用者可以之传入部分定制化属性。如下面“option bags”模式
  16. interface SquareConfig { color?: string; width?: number; }
  17. function createSquare(config: SquareConfig): {color: string; area: number} {
  18. var newSquare = {color: "white", area: 100};
  19. if (config.color) {
  20. newSquare.color = config.color;
  21. }
  22. if (config.width) {
  23. newSquare.area = config.width * config.width;
  24. }
  25. return newSquare;
  26. }
  27. var mySquare = createSquare({color: "black"});
  28. //函数类型
  29. //下面是定义的interface signature是一个接收两个string的输入参数,并返回boolean的函数类型:
  30. interface SearchFunc {
  31. (source: string, subString: string): boolean;
  32. }
  33. var mySearch: SearchFunc;
  34. mySearch = function(src: string, sub: string) {
  35. var result = src.search(sub);
  36. if (result == -1) {
  37. return false;
  38. }
  39. else {
  40. return true;
  41. }
  42. }
  43. //数组类型
  44. //类似于函数类型,TypeScript也可以描述数组类型。在数组类型中有一个’index’类型其描述数组下标的类型,以及返回值类型描述每项的类型
  45. nterface StringArray {
  46. [index: number]: string;
  47. }
  48. var myArray: StringArray;
  49. myArray = ["Bob", "Fred"]
  50. //Class类型
  51. //在C#和java中interface是很常使用的类型系统,其用来强制其实现类符合其契约
  52. interface ClockInterface {
  53. currentTime: Date;
  54. setTime(d: Date);
  55. }
  56. class Clock implements ClockInterface {
  57. currentTime: Date;
  58. setTime(d: Date) {
  59. this.currentTime = d;
  60. }
  61. constructor(h: number, m: number) { }
  62. }
  63. interface ClockInterface {
  64. new (hour: number, minute: number);
  65. }
  66. //当使用类和接口的时候,我们需要知道类有两种类型:static(静态)部分和instance(实例)部分。如果尝试一个类去实现一个带有构造签名的interface,TypeScript类型检查会提示你错误
  67. class Clock implements ClockInterface {
  68. currentTime: Date;
  69. constructor(h: number, m: number) { }//error
  70. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注