{"id":22283766,"url":"https://github.com/veaba/learn-typescript","last_synced_at":"2025-08-16T05:36:57.907Z","repository":{"id":104582193,"uuid":"163391904","full_name":"veaba/learn-typescript","owner":"veaba","description":"learn ts","archived":false,"fork":false,"pushed_at":"2020-06-01T06:13:01.000Z","size":41,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-25T19:53:23.029Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/veaba.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-12-28T09:23:41.000Z","updated_at":"2020-06-01T06:13:03.000Z","dependencies_parsed_at":null,"dependency_job_id":"93a76dd9-1cea-402f-a0b2-46e782273e89","html_url":"https://github.com/veaba/learn-typescript","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/veaba/learn-typescript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/veaba%2Flearn-typescript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/veaba%2Flearn-typescript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/veaba%2Flearn-typescript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/veaba%2Flearn-typescript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/veaba","download_url":"https://codeload.github.com/veaba/learn-typescript/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/veaba%2Flearn-typescript/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270672347,"owners_count":24625948,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-03T16:42:05.402Z","updated_at":"2025-08-16T05:36:57.877Z","avatar_url":"https://github.com/veaba.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\r\n----------------------------------------------------------\r\n## 常识及术语\r\n- `.ts`后缀文件\r\n- `.tsx`后缀文件\r\n- `.d.ts`后缀文件。用来标注js的数据库？\r\n- 没有类似 `v8`的 `typeScript` 解析引擎\r\n- 没有类似 `node.js`的 `typeScript` runtime  `type.ts` 环境\r\n- `implement`！！？？实现的意思， 类似es6中的 extends？\r\n```typescript\r\n// 这里的implements 啥意思？\r\nclass ZipCodeValidator implements StringValidator {\r\n    isAcceptable(s: string) {\r\n        return s.length === 5 \u0026\u0026 numberRegexp.test(s);\r\n    }\r\n}\r\n```\r\n## 问题\r\n\r\n1. ts 的class 如何用接口声明？\r\n\r\n2. Error:(11, 19) TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.\r\nreturn bject.assign({}, defaultConfig);\r\n\u003e  (\u003cany\u003eObject).assign({}, defaultConfig); // 或者更改target='es6'，因为es5不支持\r\n\r\n3. Error:(47, 22) TS2339: Property 'videoElement' does not exist on type 'typeof Features'.\r\n\r\n\u003e fix:private static videoElement:any=undefined;\r\n\r\n## 警告\r\n\r\n\r\n### 尝试不入参，会报错误\r\n```js\r\nfunction ge(person:any){\r\n    return 'hello,' +person\r\n}\r\nlet user = [1,3,3];\r\ndocument.body.innerHTML=ge(user)\r\n```\r\n###  vscode 的ts检查是本项目全部检查，所以如果有a文件中有某个对象的interface，另外一个文件中同名，则会包警告你新建的对象需要遵从第一个的对象interface定义的数据类型格式，否则会报错。\r\n\r\n----------------------------------------------------------\r\n## install \r\n\u003e cnpm install -g typescript  // 全局安装typescript\r\n## init\r\n\u003e tsc -init  // 初始化项目，vscode 会生产 tsconfig.json\r\n\r\n```js\r\nconst json ={\r\n  \"compilerOptions\": {\r\n    /* Basic Options */\r\n    \"target\": \"es\",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */\r\n    \"module\": \"commonjs\",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */\r\n    // \"lib\": [],                             /* Specify library files to be included in the compilation. */\r\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\r\n    // \"checkJs\": true,                       /* Report errors in .js files. */\r\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\r\n    // \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\r\n    // \"declarationMap\": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */\r\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\r\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\r\n    // \"outDir\": \"./js/\",                        /* Redirect output structure to the directory. */\r\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\r\n    // \"composite\": true,                     /* Enable project compilation */\r\n    // \"removeComments\": true,                /* Do not emit comments to output. */\r\n    // \"noEmit\": true,                        /* Do not emit outputs. */\r\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\r\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\r\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\r\n\r\n    /* Strict Type-Checking Options */\r\n    \"strict\": true,                           /* Enable all strict type-checking options. */\r\n    // \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\r\n    // \"strictNullChecks\": true,              /* Enable strict null checks. */\r\n    // \"strictFunctionTypes\": true,           /* Enable strict checking of function types. */\r\n    // \"strictBindCallApply\": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */\r\n    // \"strictPropertyInitialization\": true,  /* Enable strict checking of property initialization in classes. */\r\n    // \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\r\n    // \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\r\n\r\n    /* Additional Checks */\r\n    // \"noUnusedLocals\": true,                /* Report errors on unused locals. */\r\n    // \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\r\n    // \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\r\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\r\n\r\n    /* Module Resolution Options */\r\n    // \"moduleResolution\": \"node\",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\r\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\r\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\r\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\r\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\r\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\r\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\r\n    \"esModuleInterop\": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */\r\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\r\n\r\n    /* Source Map Options */\r\n    // \"sourceRoot\": \"\",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */\r\n    // \"mapRoot\": \"\",                         /* Specify the location where debugger should locate map files instead of generated locations. */\r\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\r\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\r\n\r\n    /* Experimental Options */\r\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\r\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\r\n  }\r\n};\r\nconsole.info(json);\r\n```\r\n## vscode 支持\r\n\u003e 拓展 tslint\r\n\u003e ctrl+shift+b 监视  ,运行task typescript run watch任务\r\n\u003e 可以生成到不同的文件夹中去\r\n## 因为使用webstorm的隐射关系，所以，这里的task运行快捷键见如下\r\n\u003e alt+shift+f10 \r\n## ts 类型[*重复bug]\r\n- string\r\n- any\r\n\r\n## interfaces 接口\r\n- 一种定义对象的类型，相当于自定义一种关于对象的数据类型格式\r\n- 形状大小都要一致\r\n\r\n```typescript\r\n  interface Person4{\r\n    name:string,\r\n    age:number\r\n  }\r\n  let tim:Person4={\r\n    name:'Tim',\r\n    age:26\r\n  };\r\n  console.log(tim)\r\n```\r\n\r\n### 可选属性\r\n### 只读属性\r\n### 额外的属性检查\r\n\r\n```typescript\r\ninterface aface{\r\n  color?:string;\r\n  width?:number;\r\n  [propName:string]:any  //支持以外的任意数量的属性\r\n}\r\n\r\n\r\n\r\n```\r\n### 类型断言\r\n\r\n\r\n### 函数类型\r\n\r\n```ts\r\n\r\ninterface SearchFnc{\r\n  (source:string,subString:string):boolean\r\n}\r\nlet mySearch:SearchFnc\r\nlet fnSearch:SearchFnc\r\n\r\nmySearch=((source:string,subString:string)):boolean=\u003e{\r\n  let result= source.search(subString)\r\n  return result\u003e-1\r\n}\r\n\r\n// 如果是箭头函数则如下：\r\n\r\nfnSearch= (source: string, subString: string)=\u003e{\r\nlet result = source.search(subString)\r\n \treturn result \u003e -1\r\n }\r\n\r\n```\r\n\r\n### 可索引类型 \r\n\r\n看不出这个玩意有个锤子用？？\r\n\r\n=》禁止数组只读吗？\r\n\r\n```ts\r\ninterface ReadonlyStringArray {\r\n    readonly [index: number]: string;\r\n}\r\nlet myArray: ReadonlyStringArray = [\"Alice\", \"Bob\"];\r\nmyArray[2] = \"Mallory\"; // error!\r\n```\r\n\r\n### 继承接口\r\n\r\n```ts\r\ninterface A{\r\n    color:string\r\n}\r\ninterface B{\r\n    width:number\r\n}\r\n\r\ninterface S extends A{\r\n    age:number\r\n}\r\ninterface X extends A,B{\r\n    heigth:number\r\n}\r\n\r\n// let a=\u003cS\u003e{}  疑问？为什么这里是\u003cB\u003e{}??\r\n// a.color=\"red\"\r\n// a.age=6969\r\n// console.log(a)\r\n\r\n// 报错\r\n// let b:S\r\n// b.age=99\r\n// b.color=\"99\"\r\n// console.log(b)\r\n\r\n\r\n```\r\n\r\n### 混合类型\r\n\r\n\r\n\r\n\r\n## generics 泛型\r\n见\u003e`generics-type.ts`\r\n\r\n\r\n使用类型变量，一种特殊变量，表示类型而不是值\r\n\r\n```typescript\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\n```\r\n\r\n上面的代码中：\r\n- 给函数添加了类型变量T，T帮助我们捕获用户传入类型（比如: number），之后就可以使用这个类型\r\n- 再次使用T作为返回值类型\r\n\r\n第一种使用的方法\r\n\r\n```ts\r\nlet output= indentity\u003cstring\u003e(\"hahaha\")\r\n```\r\n\r\n第二种使用的方法,利用了ts的类型推论（类型推导）——编译器会根据传入的参数自动地帮助用户确定T的类型\r\n```js\r\nconst output1=indentity('wakaka')\r\n```\r\n\r\n### 使用泛型变量\r\n \r\n使用泛型创建泛型函数时，编译器要求函数体必须使用这个通用的类型，必须将参数认为是任意或所有类型\r\n\r\n```ts\r\nfunction loggingIdentity\u003cT\u003e(arg: Array\u003cT\u003e): Array\u003cT\u003e {\r\n    console.log(arg.length);  // Array has a .length, so no more error\r\n    return arg;\r\n}\r\n```\r\n\r\n### 泛型类型\r\n\r\n泛型函数，有类型参数在最前面，类似函数声明\r\n\r\n```ts\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\n\r\nconst myIdentity:\u003cT\u003e(arg:T)=\u003eT=identity\r\n```\r\n\r\n也可以使用不同的泛型参数名，只要在数量上和使用方式上对应即可\r\n\r\n\r\n```ts\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\n\r\nconst myid:\u003cU\u003e(arg:U)=\u003eU=identity\r\n```\r\n\r\n带有调用签名的对象字面量来定义泛型函数：\r\n\r\n```ts\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\n\r\nlet myitidy:{\u003cT\u003e(arg:T):T}=identity\r\n```\r\n\r\n这引导我们去写第一个泛型接口。\r\n\r\n```ts\r\ninterface GenericIdentityFn {\r\n  \u003cT\u003e(arg:T):T\r\n}\r\n\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\n\r\nconst mytidy:GenericIdentityFn=identity\r\n```\r\n\r\n把泛型参数当做整个接口的参数，可清楚的知道使用的具体是哪个泛型（Dictionary\u003cT\u003e而不是dictionary），这样接口里的其他成员就能知道这个参数的类型\r\n\r\n```ts\r\ninterface GenericIdentityFn\u003cT\u003e{\r\n  (arg:T):T\r\n}\r\n\r\nfunction identity\u003cT\u003e(arg:T):T{\r\n  return arg\r\n}\r\nconst mytity:GenericIdentityFn\u003cnumber\u003e=identity\r\n\r\n```\r\n\r\n除了泛型接口，还可以创建泛型类，注意，无法创建`泛型枚举`和`泛型命名空间`\r\n\r\n### 泛型类\r\n```ts\r\nclass School\u003cT\u003e{\r\n  zeroV:T,\r\n  // 这个函数将会被复写\r\n  add:(x:T,y:T)=\u003eT\r\n}\r\nconst mySchool=new School\u003cnumber\u003e()\r\nmySchool.zeroV=0\r\nmySchool.add=function(x,y){\r\n  return x+y\r\n}\r\n\r\n```\r\n这里并没有使用它只能使用`number`，也可以其他类型\r\n\r\n\r\n```ts\r\nconst strNameric=new School\u003cstring\u003e()\r\nstrNameric.zeroV=\"\"\r\nstrNameric.add=function(x,y) {return x+y}\r\n\r\nconsole.log(strNameric.add(strNameric.zeroV,\"test\"))\r\n\r\n\r\n```\r\n\r\n### 泛型约束\r\n\r\n```ts\r\nfunction logi\u003cT\u003e(arg:T):T{\r\n  console.log(arg.length) //Error: T doesn't have .length\r\n  return arg\r\n}\r\n\r\n```\r\n\r\n可以定义一个接口描述来约束补充这个未知的类型没有某个属性，是要用接口和`extends` 关键字来说实现约束\r\n\r\n```ts\r\ninterface Lengthwise {\r\n  length:number\r\n}\r\n\r\nfunction logi\u003cT extends Lengthwise\u003e(arg:T):T{\r\n  console.log(arg.length) // Now we know it has a .length property,so no more error\r\n  return arg\r\n}\r\n\r\n```\r\n\r\n现在泛型函数被约束了，不再适用任意类型了。\r\n\r\n```ts\r\nconsole.log('===\u003elogi',logi(3)) // Error, number no .length property\r\n```\r\n\r\n需要传入符合约束类型的值，必须含有必须的属性\r\n\r\n```ts\r\nlogi({length:1,value:2})\r\n```\r\n\r\n### 泛型约束中使用类型参数\r\n\r\n你可以声明一个类型参数，且它被另一个类型参数所约束。 比如，现在我们想要用属性名从对象里获取这个属性。 并且我们想要确保这个属性存在于对象 `obj`上，因此我们需要在这两个类型之间使用约束。\r\n```ts\r\nfunction getProperty(obj:T,key:k){\r\n  return obj[key]\r\n}\r\n\r\nconst x={a:1,b:2,c:3,d:4}\r\n\r\ngetProperty(x,'a')\r\ngetProperty(x,'m') //error\r\n\r\n```\r\n### 泛型中使用类类型\r\n\r\n是TS中使用泛型创建工厂函数时，需要引用构造函数的类类型，比如\r\n\r\n```ts\r\nfunction create\u003cT\u003e(c:{new():T}):T{\r\n  return new c()\r\n}\r\n```\r\n\r\n一个高级的例子，使用原型属性推断并约束构造函数与类实例的关系\r\n```ts\r\nclass BeeKeeper {\r\n    hasMask: boolean;\r\n}\r\n\r\nclass ZooKeeper {\r\n    nametag: string;\r\n}\r\n\r\nclass Animal {\r\n    numLegs: number;\r\n}\r\n\r\nclass Bee extends Animal{\r\n  keeper:BeeKeeper\r\n}\r\n\r\nclass Lion exntends Animal{\r\n  keeper:ZooKeeper\r\n}\r\n\r\nfunction createInstance\u003cA extends Animal\u003e(c:new ()=\u003eA):A{\r\n  return new c()\r\n}\r\n\r\ncreateInstance(Lion).keeper.nametag  // typechecks!\r\ncreateInstance(Bion).keeper.hasMask  // typechecks!\r\n\r\n```\r\n\r\n\r\n\r\n## 类 classes\r\n### 概念\r\n\r\n- `class` 类，定义一个事物的抽象特点，包含 属性和方法\r\n- `object` 对象，类的实例，通过new 生成\r\n- `OOP` 面向对象：封装、继承、多态\r\n- `encapsulation封装，确保外部无法任意更改内部对象的数据，对外暴露接口`\r\n- `inheritance` 继承，子类继承父类，子类拥有父类所有特性之后，还有自己的一些\r\n- `polymoiphism` 多态，继承产生相关不同的类，有点难理解\r\n- `getter` \u0026 `setter`，用以改变属性的读取和赋值行为\r\n- `modifiers`：一些关键字，用于限定成员或类型的性质，比如`public`表示共用属性或方法，`private`则表示私有\r\n- `abstract class`抽象类，供给其他类继承的 `基础类`，且不允许被实例化，抽象方法必须在子类中被实现\r\n- `interface`接口：不同类之间公有的属性和方法，可以抽象成一个接口。接口可以被类实现，一类`只能`继承自`另一个类`，但可以实现多个接口\r\n- 类具有两个类型：静态部位类型和实例类型\r\n\r\n\r\n### 如何实现类接口？？\r\n\r\n\r\n### es6类\r\n\u003e http://es6.ruanyifeng.com/#docs/class\r\n\r\n```js\r\n  class Animal{\r\n    constructor(name){\r\n      this.name=name\r\n    }\r\n    sayHi(){\r\n      return `My name is: ${this.name}`//如果是this.name=\u003ename，则无法获取到。\r\n    }\r\n  }\r\n  let cat= new Animal('cat');\r\n  console.log(cat.sayHi());\r\n  // 类的继承\r\n  class Cat extends Animal{\r\n    constructor(name){\r\n      super(name);//调用父类的constuctor(name)\r\n      console.log(this.name)\r\n    }\r\n    sayHi1(){\r\n      return `I am sayHi1:${this.name} `\r\n    }\r\n  }\r\n\r\n  // 此时 cat 实例就有两个方法和一个实例\r\n  let cat1= new Cat('丁丁')\r\n```\r\n## enums 枚举\r\n## 基础类型\r\n- `boolean`\r\n### `number`  \r\n\u003e 接受十进制、十六进制、二进制、八进制\r\n### `string`\r\n\u003e 符号 “ ' `\r\n### `array` 数组\r\n  - `let list:number[]=[1,2,3]` 表示数字组成的数组\r\n  - `let list:Array\u003cnumber\u003e=[,2,3]` 使用数组泛型，array \u003c元素类型\u003e\r\n  - `let list:number[]=[1,'2',3]` 一个错误的标识符，数组只能包含number类型\r\n  - `let a:Array\u003cnumber|string\u003e=[1,3,'2']` 一个只包含string 和number类型的数组\r\n- 元组 Tuple\r\n  - 给数组的元素位置，定义了类型\r\n\u003e 越界情况，意思是不在之前约定的长度范围内，则类型只能使用两者之一，否则也会报错\r\n\r\n```typescript\r\nlet x =[string,number];\r\n x =['hello',100]; //ok\r\n x=[10,'helloe']//error\r\n```\r\n- 枚举 enum，对js的一个数据类型补充\r\n```typescript\r\n  enum Color {Red=1,Gree=14,Blue=399}\r\n  let c:Color=Color.Green\r\n```\r\n### `any` 任意值\r\n```typescript\r\n  let noSure:any;\r\n  noSure =\"maybe a String\";\r\n  noSure =false\r\n```\r\n### `void` 空值\r\n\u003e 常见函数没有return 返回值时，通常`void`\r\n```typescript\r\nfunction warn():void{\r\n  alert('this warning msg')\r\n}\r\n// so 你只能给他void undefined null\r\nlet unVoid:void =undefined || null\r\n```\r\n- `null和undefined`\r\n\u003e `--strickNullChecks ` 只能赋值给void和他们自己，避免很多常见问题，比如？\r\n### `Never`\r\n```typescript\r\n// 返回never的函数，必须存在无法到达的终点\r\nfunction error(msg:string):never{\r\n  throw Error(msg)\r\n}\r\n// 推断的返回值类型为 never\r\nfunction fail(){\r\n  return error(\"xxx\")\r\n}\r\n// 返回never的函数，必须存在无法到达的终点\r\nfunction infiniteLoop():never{\r\n  while(true){\r\n\tconsole.log('forever~~')\r\n  }\r\n}\r\n```\r\n### `Object` 对象\r\n\u003e 又忘记了 Object.create() 的用法了，不行呀~~记不住这些API 苦恼\r\n```typescript\r\ndeclare function create(o: object | null): void;\r\n\r\ncreate({ prop: 0 }); // OK\r\ncreate(null); // OK\r\n\r\ncreate(42); // Error\r\ncreate(\"string\"); // Error\r\ncreate(false); // Error\r\ncreate(undefined); // Error\r\n```\r\n## `function` 函数\r\n- 多余或者少于的参数，不被允许\r\n- 输入输出都考虑到数据类型\r\n```typescript\r\n  function sum(x:number,y:number):number{\r\n    return x+ y\r\n  }\r\n```\r\n- `=\u003e` 表示 左边输入类型，右边输出类型\r\n- 一个函数表达式，带输入输出的函数声明\r\n```js\r\nlet mySum:(x:number,y:number)=\u003enumber=function(x:number,y:number):number{\r\n  return x+ y\r\n}\r\n```\r\n### 使用interface 定义函数形状\r\n```typescript\r\ninterface SearchFnc{\r\n    //相当于 入参是两个，都是字符串，输出的是一个布尔值\r\n    (source:string,subString:string):boolean\r\n}\r\nlet mySearch:SearchFnc\r\nmySearch=function(x:string,y:string){\r\n    return x.search(y)!==-1\r\n}\r\n```\r\n### 可选的函数参数\r\n```typescript\r\nfunction x(x:string,y:number,x?:number|object){\r\n    // coding\r\n}\r\n```\r\n### 给参数添加一个默认值,`此时不受限制：可选参数必须接待必选参数后面`\r\n```typescript\r\nfunction x(x:string,y:number,x?:number|object=2333){\r\n    // coding\r\n}\r\n```\r\n### 剩余参数,此时items是最后一个参数\r\n```typescript\r\nfunction push(array:any[],...items:any[]){\r\n    // coding\r\n    items.forEach((item)=\u003e{\r\n      array.push(item)\r\n    })\r\n}\r\nlet a=[]\r\npush(a,1,33,34)\r\n```\r\n### 重载\r\n- 意思是先检查第一个number类型人入参\r\n- 后续再检查，具体的代码实现，还是要抄一遍\r\n```typescript\r\nfunction reverse(x: number | string): number | string|undefined {\r\n    if (typeof x === 'number') {\r\n        return Number(x.toString().split('').reverse().join(''))||'';\r\n    } else if (typeof x === 'string') {\r\n        return x.split('').reverse().join('')||'';\r\n    }\r\n}\r\nlet c = reverse(123)\r\nconsole.log(c)\r\n\r\n// 由于输入数字逆序之后还得是数字，字符依然是字符的，为此需要上做上的判断处理，但如果使用了重载定义函数的话：\r\n\r\nfunction reverse(x: number): number;//函数定义\r\nfunction reverse(x: string): string;//函数定义\r\n//函数实现，有限把精确的定义写在前面\r\nfunction reverse(x: number | string): number | string|undefined {\r\n    if (typeof x === 'number') {\r\n        return Number(x.toString().split('').reverse().join(''));\r\n    } else if (typeof x === 'string') {\r\n        return x.split('').reverse().join('');\r\n    }\r\n}\r\n//讲真的，没看出来啥。\r\n```\r\n### 断言\r\n\u003e 类型断言不是`类型转换`，`断言成` 一个联合类型中 不存在的类型是不允许的\r\n- 断言的类型只能是联合类型中的类型\r\n```typescript\r\n/**\r\n * @desc 断言\r\n * \r\n */\r\nfunction getLength(something: string | number): number {\r\n    if ((\u003cstring\u003esomething).length) {\r\n        return (\u003cstring\u003esomething).length;\r\n    } else {\r\n        return something.toString().length;\r\n    }\r\n}\r\n//error 此时，翻译器会报错,因为如果是number话，不存在length属性,但JS中，却可以不需要这个断言\r\nfunction getLength(something: string | number): number {\r\n    if (something.length) {\r\n        return (something.length;\r\n    } else {\r\n        return something.toString().length;\r\n    }\r\n}\r\n//但JS中，却可以不需要这个断言\r\nfunction getLength1(something){\r\n    if (something.length) {\r\n        return something.length;\r\n    } else {\r\n        return something.toString().length;\r\n    }\r\n}\r\ngetLength1(11);\r\ngetLength1('11')\r\n```\r\n## 内置对象\r\n\u003e typescript 内置核心库  https://github.com/Microsoft/TypeScript/tree/master/src/lib\r\n### ECMAScript 内置\r\n- Boolean\r\n- Error\r\n- Date\r\n- RegExp\r\n- ...\r\n```typescript\r\nlet b: Boolean = new Boolean(1);\r\nlet e: Error = new Error('Error occurred');\r\nlet d: Date = new Date();\r\nlet r: RegExp = /[a-z]/;\r\n```\r\n### BOM和DOM内置对象\r\n- Document\r\n- HTMLElement\r\n- Event\r\n- NodeList\r\n- ...\r\n```typescript\r\nlet body: HTMLElement = document.body;\r\nlet allDiv: NodeList = document.querySelectorAll('div');\r\ndocument.addEventListener('click', function(e: MouseEvent) {\r\n  // Do something\r\n});\r\n```\r\n### TypeScript 使用node.js\r\n\u003e`npm install @types/node --save-dev`\r\n## typeScript 的能力\r\n### 类型推断能力\r\n```typescript\r\n  let s='I am a string';\r\n  s=2333;//这里将原本的 string 类型变更为数字类型\r\n\r\n  // 以上等同于\r\n  let s:string = 'I am a string';\r\n  s=2333;\r\n\r\n  // 从第一段可看出，在ts中和原生js里面，变量的类型有了很大的变化，为此，需要这么写：\r\n  let s//自动推断为any\r\n  s='I am a string';\r\n  s=2333;\r\n  // or \r\n  let s:any;\r\n  s=\"I am a string\";\r\n  s=2333\r\n```\r\n### 联合类型\r\n\u003e 可以为该变量指定多个数据的类型\r\n\r\n```typescript\r\n  let s: string|number;\r\n  s=\"I am a String\";\r\n  s=2333;\r\n\r\n  // error\r\n  s=true\r\n```\r\n\u003e 在不知道联合类型的变量是哪个类型是，只能访问此联合类型的所有类型的共用属性或者方法，比如常见 `toString()`、`valueOf()`、`__proto__`（以上三种类型需要排除掉`null`、`undefined`）\r\n### declare 声明文件\r\n- 一般讲声明文件放到一单独的一个文件中，以`.d.ts`后缀结尾,比如`$.d.ts`\r\n- 三斜线指令表示引用声明文件，`/// \u003creference path=\"./$.d.ts\"/\u003e`\r\n- 关于jquery 给出的声明文件，见 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jquery/index.d.ts\r\n- 第三方声明文件，http://definitelytyped.org/\r\n- https://microsoft.github.io/TypeSearch/ 搜索需要的声明文件\r\n```typescript\r\n// demo\r\ndeclare var $:(selector:string)=\u003eany;\r\n$('.class')\r\n\r\n// demo\r\ndeclare var test:(t:string)=\u003eany;\r\ntest('ttt')\r\n```\r\n## 进阶\r\n### 类型别名\r\n\u003e haha，相当于整合了 `val:string|number`=\u003e `val:sb`。\r\n```typescript\r\n  // default\r\n  function t(val:string|number){\r\n    return val\r\n  }\r\n  type s=string;\r\n  type b=number\r\n  type sb=s|b\r\n  function t(val:sb){\r\n    return val\r\n  }\r\n```\r\n### `字符串` __字面量__ 类型\r\n- 字符串字面量都使用 `type`来定义\r\n```typescript\r\ntype EventName='click'|'dbclick'\r\nfunction hand(el:Element,event:EventName){\r\n  //do something\r\n}\r\nhand(document.querySelector('#d'),'click')\r\nhand(document.querySelector('#d'),'scroll')//error\r\n```\r\n## 接口\r\n- 确定属性`：` 则说明，属性名要对上，且不能多，不能少.\r\n- 可选属性`？:` 可选的，依然不允许添加未定义的属性\r\n- 任意属性 `[propName:string]:any`  任意的，但其他的属性，都要遵从此处的类型规定\r\n- 只读属性`readonly id:number`,且 一定要有该属性\r\n```typescript\r\ninterface Person_1{\r\n  firstName:'Jo'\r\n  lastName:'Gol'\r\n// 错误的示范\r\n}\r\ninterface Person1_2{\r\n    readonly id:number;\r\n    name: string;\r\n    age?: number;//因为是number，但任意类型是string，所以此处是错误的，必须将age改为string，或者 string|number。缺定义的是时候，因为缺少了age属性，所以，还有一个undefined\r\n    [propName:string]:string;//或者 此处改为 string|undefiner|number、或者 any\r\n}\r\n\r\nlet person3: Person1_2 = {\r\n    id:2333,\r\n    name: 'Tom',\r\n    aget: 'x'\r\n};\r\n// error 如果在ts对readonly 属性赋值。则会报错\r\nperson3.id=11111 //error\r\n```\r\n## modules\r\n- `模块里面不要用命名空间`\r\n- `命名空间使用模块，几乎没有什么价值`\r\n- `文件的顶层声明是export namespace Foo { ... }（删除Foo并把所有内容向上层移动一层）` \r\n- `文件只有一个export class或export function （考虑使用export default）`\r\n- `多个文件的顶层具有同样的export namespace Foo { （不要以为这些会合并到一个Foo中！）`\r\n### 关于模块的tsc命令\r\n```shell\r\n\ttsc --module commonkjs test.ts\r\n\r\n```\r\n### 将整个模块导入到一个变量\r\n```typescript\r\n\timport * as xxx from 'xxx'\r\n\tlet tt= new xxx.alert('喵~~')\r\n```\r\n### 具有副作用的导入模块\r\n\u003e import './t.ts'\r\n\r\n### 关于export default\r\n- export导出一个值\r\n\u003e export default '1231'\r\n### `export =` 和`import = require()`\r\n\r\n\u003e export = aVar ，此时需要使用ts语法  import module= require('module')\r\n\r\n\u003e import a_var = './xx'\r\n\r\n### 生成模块代码\r\n- simpleModule.ts\r\n```js\r\nimport m= require('mode)\r\nexport let t=m.t+1\r\n```\r\n- require.js(AMD)\r\n```js\r\ndefine(['require','exports','./mod'],function( require,exports,mod_1) {\r\n  exports.t=mod_1.test+1\r\n})\r\n\r\n```\r\n- node.js(common.js)/SimpleModule.js\r\n```js\r\nlet mod=  require('mod')\r\nexport.t= mod.test+1\r\n```\r\n- UMD `真长啊~~`\r\n```js\r\n(function (factory) {\r\n    if (typeof module === \"object\" \u0026\u0026 typeof module.exports === \"object\") {\r\n        let v = factory(require, exports); if (v !== undefined) module.exports = v;\r\n    }\r\n    else if (typeof define === \"function\" \u0026\u0026 define.amd) {\r\n        define([\"require\", \"exports\", \"./mod\"], factory);\r\n    }\r\n})(function (require, exports) {\r\n    let mod_1 = require(\"./mod\");\r\n    exports.t = mod_1.something + 1;\r\n});\r\n```\r\n- SystemJS\r\n\r\n```js\r\n\r\nSystem.register([\"./mod\"], function(exports_1) {\r\n    let mod_1;\r\n    let t;\r\n    return {\r\n        setters:[\r\n            function (mod_1_1) {\r\n                mod_1 = mod_1_1;\r\n            }],\r\n        execute: function() {\r\n            exports_1(\"t\", t = mod_1.something + 1);\r\n        }\r\n    }\r\n});\r\n```\r\n\r\n- Native ECMAScript 2015 modules SimpleModule.js，es6的方式\r\n```js\r\nimport { something } from \"./mod\";\r\nexport let t = something + 1;\r\n\r\n```\r\n### 外部模块\r\n- node.d.ts\r\n```typescript\r\ndeclare module \"url\" {\r\n    export interface Url {\r\n        protocol?: string;\r\n        hostname?: string;\r\n        pathname?: string;\r\n    }\r\n\r\n    export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;\r\n}\r\n\r\ndeclare module \"path\" {\r\n    export function normalize(p: string): string;\r\n    export function join(...paths: any[]): string;\r\n    export let sep: string;\r\n}\r\n```\r\n- app.ts\r\n```typescript\r\n/// \u003creference path=\"node.d.ts\"/\u003e\r\nimport * as URL from \"url\";\r\nlet myUrl = URL.parse(\"http://www.typescriptlang.org\");\r\n```\r\n- 支持通配符 \r\n\t- \"*!text\"\r\n\t- \"json!*\"\r\n- UMD \r\n## 命名空间\r\n- `tsc --outFile sample.js Test.ts` 将所有输入文件编译为一个输出文件，需要 `--outFile`标记\r\n## 命名空间和模块\r\n- TypeScript里模块的一个特点是不同的模块永远也不会在相同的作用域内使用相同的名字\r\n- 不应该对模块使用命名空间\r\n \r\n错误的使用 \r\n```typescript\r\n\r\n//a.ts\r\nexport namespace Shapes {\r\n    export class xxx{\r\n\t}\r\n}\r\n\r\n// b.ts\r\nimport * as shapes from \"./shapes\";\r\nlet t = new shapes.Shapes.xxx();\r\n```\r\n\r\n\r\n修正的使用\r\n```typescript\r\n\r\n//a.ts\r\nexport class xxx{\r\n}\r\n\r\n// b.ts\r\nimport * as shapes from \"./shapes\";\r\nlet t = new shapes.xxx();\r\n\r\n```\r\n## 声明合并\r\n- 类不能与其他类或变量合并\r\n\r\n|声明类型|Namespace|Type|Value|\r\n|----|----|----|----|\r\n|Namespace命名空间|×||×|\r\n|Class类||×|x|\r\n|Enum枚举||×|x|\r\n|Interface接口||×||\r\n|Type Alias类型别名||×||\r\n|Function函数|||×|\r\n|Variable变量|||×|\r\n\r\n### interface 合并\r\n```typescript\r\ninterface Box {\r\n  height:number,\r\n  width:number\r\n}\r\ninterface Box {\r\n  size:number\r\n}\r\nlet box:Box={\r\n    height:33,\r\n    width:99,\r\n    size:666\r\n}\r\n```\r\n### namespace 合并\r\n- `从其他命名空间合并进来的成员无法访问非导出成员`\r\n```typescript\r\n\tnamespace Animals{\r\n    \texport class God {\r\n    \t  \r\n    \t}\r\n\t}\r\n\tnamespace Animals{\r\n    \texport class Cat {\r\n    \t  \r\n    \t}\r\n\t}\r\n\t\r\n\t//=\u003e\u003e\r\n\tnamespace Animals{\r\n    \texport class God{\r\n    \t    \r\n    \t}\r\n    \texport class Cat {\r\n    \t  \r\n    \t}\r\n\t}\r\n```\r\n### 命名空间、类、函数、枚举合并\r\n\r\n### 全局拓展\r\n```typescript\r\n\tdeclare global{\r\n    \tinterface Array\u003cT\u003e {\r\n    \t    //Do something\r\n    \t}\r\n\t}\r\n```\r\n\r\n## 书写d.ts 文件 `暂缺`\r\n\r\n## JSX\r\n\u003e facebook 的React 使用jsx，从而导致流行起来\r\n\r\n### typescript三种JSX模式\r\n- hsc --jsx 做标记\r\n\r\n|模式|输入|输出|拓展名|\r\n|----|----|----|----|\r\n|preserve[prɪˈzɜ:rv]|`\u003cdiv/\u003e`|`\u003cdiv/\u003e`|`.jsx`|\r\n|react|`\u003cdiv/\u003e`|`React.createElement('div')`|`js`|\r\n|react-native|`\u003cdiv/\u003e`|`\u003cdiv/\u003e`|`js`|\r\n\r\n### as 操作符 \r\n\u003e https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/JSX.html\r\n## Decorators 装饰！！`常见这个`\r\n\r\n\r\n## tsc命令选项\r\n```cmd \r\nSyntax:   tsc [options] [file...]\r\n\r\nExamples: tsc hello.ts\r\n          tsc --outFile file.js file.ts\r\n          tsc @args.txt\r\n          tsc --build tsconfig.json\r\n\r\nOptions:\r\n -h, --help                                         Print this message.\r\n -w, --watch                                        Watch input files.\r\n --pretty                                           Stylize errors and messages using color and context (experimental).\r\n --all                                              Show all compiler options.\r\n -v, --version                                      Print the compiler's version.\r\n --init                                             Initializes a TypeScript project and creates a tsconfig.json file.\r\n -p FILE OR DIRECTORY, --project FILE OR DIRECTORY  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.\r\n -b, --build                                        Build one or more projects and their dependencies, if out of date\r\n -t VERSION, --target VERSION                       Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.\r\n -m KIND, --module KIND                             Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.\r\n --lib                                              Specify library files to be included in the compilation.\r\n                                                      'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown'\r\n 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint'\r\n --allowJs                                          Allow javascript files to be compiled.\r\n --jsx KIND                                         Specify JSX code generation: 'preserve', 'react-native', or 'react'.\r\n -d, --declaration                                  Generates corresponding '.d.ts' file.\r\n --declarationMap                                   Generates a sourcemap for each corresponding '.d.ts' file.\r\n --sourceMap                                        Generates corresponding '.map' file.\r\n --outFile FILE                                     Concatenate and emit output to single file.\r\n --outDir DIRECTORY                                 Redirect output structure to the directory.\r\n --removeComments                                   Do not emit comments to output.\r\n --noEmit                                           Do not emit outputs.\r\n --strict                                           Enable all strict type-checking options.\r\n --noImplicitAny                                    Raise error on expressions and declarations with an implied 'any' type.\r\n --strictNullChecks                                 Enable strict null checks.\r\n --strictFunctionTypes                              Enable strict checking of function types.\r\n --strictBindCallApply                              Enable strict 'bind', 'call', and 'apply' methods on functions.\r\n --strictPropertyInitialization                     Enable strict checking of property initialization in classes.\r\n --noImplicitThis                                   Raise error on 'this' expressions with an implied 'any' type.\r\n --alwaysStrict                                     Parse in strict mode and emit \"use strict\" for each source file.\r\n --noUnusedLocals                                   Report errors on unused locals.\r\n --noUnusedParameters                               Report errors on unused parameters.\r\n --noImplicitReturns                                Report error when not all code paths in function return a value.\r\n --noFallthroughCasesInSwitch                       Report errors for fallthrough cases in switch statement.\r\n --types                                            Type declaration files to be included in compilation.\r\n --esModuleInterop                                  Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.\r\n @\u003cfile\u003e                                            Insert command line options and files from a file.\r\n\r\n```\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fveaba%2Flearn-typescript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fveaba%2Flearn-typescript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fveaba%2Flearn-typescript/lists"}