cnpm i typescript -g
複製代碼
tsc helloworld.ts
複製代碼
tsc --init
複製代碼
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. 指定ECMAScript的目標版本*/
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. 指定模塊代碼的生成方式*/
// "lib": [], /* Specify library files to be included in the compilation. 指定編譯的時候用來包含的編譯文件*/
// "allowJs": true, /* Allow javascript files to be compiled. 容許編譯JS文件*/
// "checkJs": true, /* Report errors in .js files. 在JS中包括錯誤*/
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. 指定JSX代碼的生成方式 是保留仍是react-native或者react*/
// "declaration": true, /* Generates corresponding '.d.ts' file.生成相應的類型聲明文件 */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. 爲每一個類型聲明文件生成相應的sourcemap*/
// "sourceMap": true, /* Generates corresponding '.map' file. 生成對應的map文件 */
// "outFile": "./", /* Concatenate and emit output to single file. 合併而且把編譯後的內容輸出 到一個文件裏*/
// "outDir": "./", /* Redirect output structure to the directory.按原始結構輸出到目標目錄 */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. 指定輸入文件的根目錄,用--outDir來控制輸出的目錄結構*/
// "composite": true, /* Enable project compilation 啓用項目編譯*/
// "removeComments": true, /* Do not emit comments to output. 移除註釋*/
// "noEmit": true, /* Do not emit outputs. 不要輸出*/
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. 當目標是ES5或ES3的時候提供對for-of、擴展運算符和解構賦值中對於迭代器的完整支持*/
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule').r把每個文件轉譯成一個單獨的模塊 */
/* Strict Type-Checking Options */
//"strict": true, /* Enable all strict type-checking options. 啓用徹底的嚴格類型檢查 */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. 不能使用隱式的any類型*/
// "strictNullChecks": true, /* Enable strict null checks. 啓用嚴格的NULL檢查*/
// "strictFunctionTypes": true, /* Enable strict checking of function types. 啓用嚴格的函數類型檢查*/
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions.啓用函數上嚴格的bind call 和apply方法 */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. 啓用類上初始化屬性檢查*/
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type.在默認的any中調用 this表達式報錯 */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. 在嚴格模式下解析而且向每一個源文件中發射use strict*/
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. 有未使用到的本地變量時報錯 */
// "noUnusedParameters": true, /* Report errors on unused parameters. 有未使用到的參數時報錯*/
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. 當不是全部的代碼路徑都有返回值的時候報錯*/
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. 在switch表達式中沒有替代的case會報錯 */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). 指定模塊的解析策略 node classic*/
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. 在解析非絕對路徑模塊名的時候的基準路徑*/
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. 一些路徑的集合*/
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. 根目錄的列表,在運行時用來合併內容*/
// "typeRoots": [], /* List of folders to include type definitions from. 用來包含類型聲明的文件夾列表*/
// "types": [], /* Type declaration files to be included in compilation.在編譯的時候被包含的類型聲明 */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking.當沒有默認導出的時候容許默認導入,這個在代碼執行的時候沒有做用,只是在類型檢查的時候生效 */
//"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.*/
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks.不要symlinks解析的真正路徑 */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. 指定ts文件位置*/
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. 指定 map文件存放的位置 */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. 源文件和sourcemap 文件在同一文件中,而不是把map文件放在一個單獨的文件裏*/
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. 源文件和sourcemap 文件在同一文件中*/
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. 啓動裝飾器*/
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
複製代碼
tsc
複製代碼
let married: boolean=false;
複製代碼
let age: number=10;
複製代碼
let firstname: string='zfpx';
複製代碼
let arr2: number[]=[4,5,6];
let arr3: Array<number>=[7,8,9];
複製代碼
數量
和類型
的數組let zhufeng:[string,number] = ['zhufeng',5];
zhufeng[0].length;
zhufeng[1].toFixed(2);
複製代碼
元組 | 數組 |
---|---|
每一項能夠是不一樣的類型 | 每一項都是同一種類型 |
有預約義的長度 | 沒有長度限制 |
用於表示一個固定的結構 | 用於表示一個列表 |
const animal:[string,number,boolean] = ['zhufeng',10,true];
複製代碼
enum Gender{
GIRL,
BOY
}
console.log(`李雷是${Gender.BOY}`);
console.log(`韓梅梅是${Gender.GIRL}`);
enum Week{
MONDAY=1,
TUESDAY=2
}
console.log(`今天是星期${Week.MONDAY}`);
複製代碼
const enum Colors {
Red,
Yellow,
Blue
}
let myColors = [Colors.Red, Colors.Yellow, Colors.Blue];
複製代碼
const enum Color {Red, Yellow, Blue = "blue".length};
複製代碼
any
就是能夠賦值給任意類型any
let root:any=document.getElementById('root');
root.style.color='red';
複製代碼
let root:(HTMLElement|null)=document.getElementById('root');
root!.style.color='red';//非空斷言操做符
複製代碼
strictNullChecks
參數用於新的嚴格空檢查模式,在嚴格空檢查模式下, null 和 undefined 值都不屬於任何一個類型,它們只能賦值給本身這種類型或者 anylet x: number;
x = 1;
x = undefined;
x = null;
let y: number | null | undefined;
y = 1;
y = undefined;
y = null;
複製代碼
function greeting(name:string):void {
console.log('hello',name);
//當咱們聲明一個變量類型是 void 的時候,它的非嚴格模式(strictNullChecks:false)下僅能夠被賦值爲 null 和 undefined
//嚴格模式(strictNullChecks:true)下只能返回undefined
//return null;
//return undefined;
}
複製代碼
never是其它類型(null undefined)的子類型,表明不會出現的值javascript
// 返回never的函數 必須存在 沒法達到( unreachable ) 的終點
function error(message: string): never {
throw new Error(message);
}
let result1 = error('hello');
// 由類型推論獲得返回值爲 never
function fail() {
return error("Something failed");
}
let result = fail();
// 返回never的函數 必須存在 沒法達到( unreachable ) 的終點
function infiniteLoop(): never {
while (true) {}
}
複製代碼
// Compiled with --strictNullChecks
function fn(x: number | string) {
if (typeof x === 'number') {
// x: number 類型
} else if (typeof x === 'string') {
// x: string 類型
} else {
// x: never 類型
// --strictNullChecks 模式下,這裏的代碼將不會被執行,x 沒法被觀察
}
}
複製代碼
let username2;
username2 = 10;
username2 = 'zhufeng';
username2 = null;
複製代碼
let name = 'zhufeng';
console.log(name.toUpperCase());
console.log((new String('zhufeng')).toUpperCase());
複製代碼
let isOK: boolean = true; // 編譯經過
let isOK: boolean = Boolean(1) // 編譯經過
let isOK: boolean = new Boolean(1); // 編譯失敗 指望的 isOK 是一個原始數據類型
複製代碼
let name: string | number;
console.log(name.toString());
name = 3;
console.log(name.toFixed(2));
name = 'zhufeng';
console.log(name.length);
export {};
複製代碼
let name: string | number;
console.log((name as string).length);
console.log((name as number).toFixed(2));
console.log((name as boolean));
複製代碼
type ZType = 1 | 'One'|true;
let t1:ZType = 1;
let t2:ZType = 'One';
let t3:ZType = true;
複製代碼
幾個字符串
中的一個, 聯合類型(Union Types)表示取值能夠爲多種類型
中的一種function hello(name:string):void {
console.log('hello',name);
}
hello('zfpx');
複製代碼
type GetUsernameFunction = (x:string,y:string)=>string;
let getUsername:GetUsernameFunction = function(firstName,lastName){
return firstName + lastName;
}
複製代碼
let hello2 = function (name:string):void {
console.log('hello2',name);
return undefined;
}
hello2('zfpx');
複製代碼
在TS中函數的形參和實參必須同樣,不同就要配置可選參數,並且必須是最後一個參數前端
function print(name:string,age?:number):void {
console.log(name,age);
}
print('zfpx');
複製代碼
function ajax(url:string,method:string='GET') {
console.log(url,method);
}
ajax('/users');
複製代碼
function sum(...numbers:number[]) {
return numbers.reduce((val,item)=>val+=item,0);
}
console.log(sum(1,2,3));
複製代碼
let obj: any={};
function attr(val: string): void;
function attr(val: number): void;
function attr(val:any):void {
if (typeof val === 'string') {
obj.name=val;
} else {
obj.age=val;
}
}
attr('zfpx');
attr(9);
attr(true);
console.log(obj);
複製代碼
class Person{
name:string;
getName():void{
console.log(this.name);
}
}
let p1 = new Person();
p1.name = 'zhufeng';
p1.getName();
複製代碼
class User {
myname:string;
constructor(myname: string) {
this.myname = myname;
}
get name() {
return this.myname;
}
set name(value) {
this.myname = value;
}
}
let user = new User('zhufeng');
user.name = 'jiagou';
console.log(user.name);
複製代碼
"use strict";
var User = /** @class */ (function () {
function User(myname) {
this.myname = myname;
}
Object.defineProperty(User.prototype, "name", {
get: function () {
return this.myname;
},
set: function (value) {
this.myname = value;
},
enumerable: true,
configurable: true
});
return User;
}());
var user = new User('zhufeng');
user.name = 'jiagou';
console.log(user.name);
複製代碼
class User {
constructor(public myname: string) {}
get name() {
return this.myname;
}
set name(value) {
this.myname = value;
}
}
let user = new User('zhufeng');
console.log(user.name);
user.name = 'jiagou';
console.log(user.name);
複製代碼
構造函數
中初始化常量
標誌符,其值不能被從新分配編譯
階段進行代碼檢查。而 const 則會在運行時
檢查(在支持 const 語法的 JavaScript 運行時環境中)class Animal {
public readonly name: string
constructor(name:string) {
this.name = name;
}
changeName(name:string){
this.name = name;
}
}
let a = new Animal('zhufeng');
a.changeName('jiagou');
複製代碼
class Person {
name: string;//定義實例的屬性,默認省略public修飾符
age: number;
constructor(name:string,age:number) {//構造函數
this.name=name;
this.age=age;
}
getName():string {
return this.name;
}
setName(name:string): void{
this.name=name;
}
}
class Student extends Person{
no: number;
constructor(name:string,age:number,no:number) {
super(name,age);
this.no=no;
}
getNo():number {
return this.no;
}
}
let s1=new Student('zfpx',10,1);
console.log(s1);
複製代碼
class Father {
public name: string; //類裏面 子類 其它任何地方外邊均可以訪問
protected age: number; //類裏面 子類 均可以訪問,其它任何地方不能訪問
private money: number; //類裏面能夠訪問, 子類和其它任何地方都不能夠訪問
constructor(name:string,age:number,money:number) {//構造函數
this.name=name;
this.age=age;
this.money=money;
}
getName():string {
return this.name;
}
setName(name:string): void{
this.name=name;
}
}
class Child extends Father{
constructor(name:string,age:number,money:number) {
super(name,age,money);
}
desc() {
console.log(`${this.name} ${this.age} ${this.money}`);
}
}
let child = new Child('zfpx',10,1000);
console.log(child.name);
console.log(child.age);
console.log(child.money);
複製代碼
class Father {
static className='Father';
static getClassName() {
return Father.className;
}
public name: string;
constructor(name:string) {//構造函數
this.name=name;
}
}
console.log(Father.className);
console.log(Father.getClassName());
複製代碼
abstract class Animal {
name!:string;
abstract speak():void;
}
class Cat extends Animal{
speak(){
console.log('喵喵喵');
}
}
let animal = new Animal();//Cannot create an instance of an abstract class
animal.speak();
let cat = new Cat();
cat.speak();
複製代碼
訪問控制修飾符 | private protected public |
---|---|
只讀屬性 | readonly |
靜態屬性 | static |
抽象類、抽象方法 | abstract |
abstract class Animal{
name:string;
constructor(name:string){
this.name = name;
}
abstract speak():void;
}
interface Flying{
fly():void
}
class Duck extends Animal implements Flying{
speak(){
console.log('汪汪汪');
}
fly(){
console.log('我會飛');
}
}
let duck = new Duck('zhufeng');
duck.speak();
duck.fly();
複製代碼
abstract class Animal{
abstract speak():void;
}
class Dog extends Animal{
speak(){
console.log('小狗汪汪汪');
}
}
class Cat extends Animal{
speak(){
console.log('小貓喵喵喵');
}
}
let dog=new Dog();
let cat=new Cat();
dog.speak();
cat.speak();
複製代碼
class Animal{
speak(word:string):string{
return '動做叫:'+word;
}
}
class Cat extends Animal{
speak(word:string):string{
return '貓叫:'+word;
}
}
let cat = new Cat();
console.log(cat.speak('hello'));
//--------------------------------------------
function double(val:number):number
function double(val:string):string
function double(val:any):any{
if(typeof val == 'number'){
return val *2;
}
return val + val;
}
let r = double(1);
console.log(r);
複製代碼
class Animal{
speak(word:string):string{
return 'Animal: '+word;
}
}
class Cat extends Animal{
speak(word:string):string{
return 'Cat:'+word;
}
}
class Dog extends Animal{
speak(word:string):string{
return 'Dog:'+word;
}
}
let cat = new Cat();
console.log(cat.speak('hello'));
let dog = new Dog();
console.log(dog.speak('hello'));
複製代碼
行爲的抽象
,另外能夠用來描述對象的形狀
//接口能夠用來描述`對象的形狀`,少屬性或者多屬性都會報錯
interface Speakable{
speak():void;
name?:string;//?表示可選屬性
}
let speakman:Speakable = {
speak(){},//少屬性會報錯
name,
age//多屬性也會報錯
}
複製代碼
//接口能夠在面向對象編程中表示爲行爲的抽象
interface Speakable{
speak():void;
}
interface Eatable{
eat():void
}
//一個類能夠實現多個接口
class Person implements Speakable,Eatable{
speak(){
console.log('Person說話');
}
eat(){}
}
class TangDuck implements Speakable{
speak(){
console.log('TangDuck說話');
}
eat(){}
}
複製代碼
//沒法預先知道有哪些新的屬性的時候,可使用 `[propName:string]:any`,propName名字是任意的
interface Person {
readonly id: number;
name: string;
[propName: string]: any;
}
let p1 = {
id:1,
name:'zhufeng',
age:10
}
複製代碼
interface Speakable {
speak(): void
}
interface SpeakChinese extends Speakable {
speakChinese(): void
}
class Person implements SpeakChinese {
speak() {
console.log('Person')
}
speakChinese() {
console.log('speakChinese')
}
}
複製代碼
interface Person{
readonly id:number;
name:string
}
let tom:Person = {
id :1,
name:'zhufeng'
}
tom.id = 1;
複製代碼
interface discount{
(price:number):number
}
let cost:discount = function(price:number):number{
return price * .8;
}
複製代碼
interface UserInterface {
[index:number]:string
}
let arr:UserInterface = ['zfpx1','zfpx2'];
console.log(arr);
interface UserInterface2 {
[index:string]:string
}
let obj:UserInterface2 = {name:'zhufeng'};
複製代碼
interface Speakable {
name: string;
speak(words: string): void
}
class Dog implements Speakable {
name!: string;
speak(words:string) {
console.log(words);
}
}
let dog = new Dog();
dog.speak('汪汪汪');
複製代碼
class Animal{
constructor(public name:string){
}
}
interface WithNameClass{
new(name:string):Animal
}
function createAnimal(clazz:WithNameClass,name:string){
return new clazz(name);
}
let a = createAnimal(Animal,'zhufeng');
console.log(a.name);
複製代碼
T
做用域只限於函數內部使用function createArray(length: number, value: any): Array<any> {
let result: any = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
let result = createArray(3,'x');
console.log(result);
複製代碼
使用了泛型java
function createArray<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
let result = createArray2<string>(3,'x');
console.log(result);
複製代碼
arguments
function sum(...parameters: number[]) {
let args: IArguments = arguments;
for (let i = 0; i < args.length; i++) {
console.log(args[i]);
}
}
sum(1, 2, 3);
let root = document.getElementById('root');
let children: HTMLCollection = (root as HTMLElement).children;
children.length;
let nodeList: NodeList = (root as HTMLElement).childNodes;
nodeList.length;
複製代碼
class MyArray<T>{
private list:T[]=[];
add(value:T) {
this.list.push(value);
}
getMax():T {
let result=this.list[0];
for (let i=0;i<this.list.length;i++){
if (this.list[i]>result) {
result=this.list[i];
}
}
return result;
}
}
let arr=new MyArray();
arr.add(1); arr.add(2); arr.add(3);
let ret = arr.getMax();
console.log(ret);
複製代碼
interface Calculate{
<T>(a:T,b:T):T
}
let add:Calculate = function<T>(a:T,b:T){
return a;
}
add<number>(1,2);
複製代碼
function swap<A,B>(tuple:[A,B]):[B,A]{
return [tuple[1],tuple[0]];
}
let swapped = swap<string,number>(['a',1]);
console.log(swapped);
console.log(swapped[0].toFixed(2));
console.log(swapped[1].length);
複製代碼
function createArray3<T=number>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
let result2 = createArray3(3,'x');
console.log(result2);
複製代碼
function logger<T>(val: T) {
console.log(val.length); //直接訪問會報錯
}
//可讓泛型繼承一個接口
interface LengthWise {
length: number
}
//可讓泛型繼承一個接口
function logger2<T extends LengthWise>(val: T) {
console.log(val.length)
}
logger2('zhufeng');
logger2(1);
複製代碼
interface Cart<T>{
list:T[]
}
let cart:Cart<{name:string,price:number}> = {
list:[{name:'zhufeng',price:10}]
}
console.log(cart.list[0].name,cart.list[0].price);
複製代碼
type Cart<T> = {list:T[]} | T[];
let c1:Cart<string> = {list:['1']};
let c2:Cart<number> = [1];
複製代碼
Duck-Check
,就是說只要目標類型中聲明的屬性變量在源類型中都存在就是兼容的interface Animal {
name: string;
age: number;
}
interface Person {
name: string;
age: number;
gender: number
}
// 要判斷目標類型`Person`是否可以兼容輸入的源類型`Animal`
function getName(animal: Animal): string {
return animal.name;
}
let p = {
name: 'zhufeng',
age: 10,
gender: 0
}
getName(p);
//只有在傳參的時候兩個變量之間纔會進行兼容性的比較,賦值的時候並不會比較,會直接報錯
let a: Animal = {
name: 'zhufeng',
age: 10,
gender: 0
}
複製代碼
//基本數據類型也有兼容性判斷
let num : string|number;
let str:string='zhufeng';
num = str;
//只要有toString()方法就能夠賦給字符串變量
let num2 : {
toString():string
}
let str2:string='jiagour';
num2 = str2;
複製代碼
class Animal{
name:string
}
class Bird extends Animal{
swing:number
}
let a:Animal;
a = new Bird();
let b:Bird;
//並非父類兼容子類,子類不兼容父類
b = new Animal();
複製代碼
class Animal{
name:string
}
//若是父類和子類結構同樣,也能夠的
class Bird extends Animal{}
let a:Animal;
a = new Bird();
let b:Bird;
b = new Animal();
複製代碼
//甚至沒有關係的兩個類的實例也是能夠的
class Animal{
name:string
}
class Bird{
name:string
}
let a:Animal ;
a = new Bird();
let b:Bird;
b = new Animal();
複製代碼
type sumFunc = (a:number,b:number)=>number;
let sum:sumFunc;
function f1(a:number,b:number):number{
return a+b;
}
sum = f1;
//能夠省略一個參數
function f2(a:number):number{
return a;
}
sum = f2;
//能夠省略二個參數
function f3():number{
return 0;
}
sum = f3;
//多一個參數可不行
function f4(a:number,b:number,c:number){
return a+b+c;
}
sum = f4;
複製代碼
type GetPerson = ()=>{name:string,age:number};
let getPerson:GetPerson;
//返回值同樣能夠
function g1(){
return {name:'zhufeng',age:10};
}
getPerson = g1;
//返回值多一個屬性也能夠
function g2(){
return {name:'zhufeng',age:10,gender:'male'};
}
getPerson = g2;
//返回值少一個屬性可不行
function g3(){
return {name:'zhufeng'};
}
getPerson = g3;
//由於有可能要調用返回值上的方法
getPerson().age.toFixed();
複製代碼
type LogFunc = (a:number|string)=>void;
let log:LogFunc;
function log1(a:number|string|boolean){
console.log(a);
}
//目標若是可以兼容源就是能夠的
log = log1;
複製代碼
//接口內容爲空沒用到泛型的時候是能夠的
//1.接口內容爲空沒用到泛型的時候是能夠的
interface Empty<T>{}
let x!:Empty<string>;
let y!:Empty<number>;
x = y;
//2.接口內容不爲空的時候不能夠
interface NotEmpty<T>{
data:T
}
let x1!:NotEmpty<string>;
let y1!:NotEmpty<number>;
x1 = y1;
//實現原理以下,稱判斷具體的類型再判斷兼容性
interface NotEmptyString{
data:string
}
interface NotEmptyNumber{
data:number
}
let xx2!:NotEmptyString;
let yy2!:NotEmptyNumber;
xx2 = yy2;
複製代碼
//數字能夠賦給枚舉
enum Colors {Red,Yellow}
let c:Colors;
c = Colors.Red;
c = 1;
c = '1';
//枚舉值能夠賦給數字
let n:number;
n = 1;
n = Colors.Red;
複製代碼
function double(input: string | number | boolean) {
if (typeof input === 'string') {
return input + input;
} else {
if (typeof input === 'number') {
return input * 2;
} else {
return !input;
}
}
}
複製代碼
class Animal {
name!: string;
}
class Bird extends Animal {
swing!: number
}
function getName(animal: Animal) {
if (animal instanceof Bird) {
console.log(animal.swing);
} else {
console.log(animal.name);
}
}
複製代碼
strictNullChecks
選項,那麼對於可能爲null的變量不能調用它上面的方法和屬性function getFirstLetter(s: string | null) {
//第一種方式是加上null判斷
if (s == null) {
return '';
}
//第二種處理是增長一個或的處理
s = s || '';
return s.charAt(0);
}
//它並不能處理一些複雜的判斷,須要加非空斷言操做符
function getFirstLetter2(s: string | null) {
function log() {
console.log(s!.trim());
}
s = s || '';
log();
return s.charAt(0);
}
複製代碼
a?.b; //若是a是null/undefined,那麼返回undefined,不然返回a.b的值.
a == null ? undefined : a.b;
a?.[x]; //若是a是null/undefined,那麼返回undefined,不然返回a[x]的值
a == null ? undefined : a[x];
a?.b(); // 若是a是null/undefined,那麼返回undefined
a == null ? undefined : a.b(); //若是a.b不函數的話拋類型錯誤異常,不然計算a.b()的結果
a?.(); //若是a是null/undefined,那麼返回undefined
a == null ? undefined : a(); //若是A不是函數會拋出類型錯誤
//不然 調用a這個函數
複製代碼
鏈判斷運算符 還處於 stage1 階段,TS 也暫時不支持node
interface WarningButton{
class:'warning',
text1:'修改'
}
interface DangerButton{
class:'danger',
text2:'刪除'
}
type Button = WarningButton|DangerButton;
function getButton(button:Button){
if(button.class=='warning'){
console.log(button.text1);
}
if(button.class=='danger'){
console.log(button.text2);
}
}
複製代碼
interface Bird {
swing: number;
}
interface Dog {
leg: number;
}
function getNumber(x: Bird | Dog) {
if ("swing" in x) {
return x.swing;
}
return x.leg;
}
複製代碼
parameterName is Type
這種形式,其中 parameterName
必須是當前函數簽名裏的一個參數名`interface Bird {
swing: number;
}
interface Dog {
leg: number;
}
//沒有相同字段能夠定義一個類型保護函數
function isBird(x:Bird|Dog): x is Bird{
return (<Bird>x).swing == 2;
return (x as Bird).swing == 2;
}
function getAnimal(x: Bird | Dog) {
if (isBird(x)) {
return x.swing;
}
return x.leg;
}
複製代碼
interface Bird {
name: string,
fly(): void
}
interface Person {
name: string,
talk(): void
}
type BirdPerson = Bird & Person;
let p: BirdPerson = { name: 'zhufeng', fly() { }, talk() { } };
p.fly;
p.name
p.talk;
複製代碼
//先定義類型,再定義變量
type People = {
name:string,
age:number,
gender:string
}
let p1:People = {
name:'zhufeng',
age:10,
gender:'male'
}
複製代碼
//先定義變量,再定義類型
let p1 = {
name:'zhufeng',
age:10,
gender:'male'
}
type People = typeof p1;
function getName(p:People):string{
return p.name;
}
getName(p1);
複製代碼
interface Person{
name:string;
age:number;
job:{
name:string
};
interests:{name:string,level:number}[]
}
let FrontEndJob:Person['job'] = {
name:'前端工程師'
}
let interestLevel:Person['interests'][0]['level'] = 2;
複製代碼
interface Person{
name:string;
age:number;
gender:'male'|'female';
}
//type PersonKey = 'name'|'age'|'gender';
type PersonKey = keyof Person;
function getValueByKey(p:Person,key:PersonKey){
return p[key];
}
let val = getValueByKey({name:'zhufeng',age:10,gender:'male'},'name');
console.log(val);
複製代碼
interface Person{
name:string;
age:number;
gender:'male'|'female';
}
//批量把一個接口中的屬性都變成可選的
type PartPerson = {
[Key in keyof Person]?:Person[Key]
}
let p1:PartPerson={};
//也可使用泛型
type Part<T> = {
[key in keyof T]?:T[key]
}
let p2:Part<Person>={};
複製代碼
type Partial<T> = { [P in keyof T]?: T[P] };
interface A {
a1: string;
a2: number;
a3: boolean;
}
type aPartial = Partial<A>;
const a: aPartial = {}; // 不會報錯
複製代碼
//type Required<T> = { [P in keyof T]-?: T[P] };
interface Person{
name:string;
age:number;
gender?:'male'|'female';
}
/**
* type Require<T> = { [P in keyof T]-?: T[P] };
*/
let p:Required<Person> = {
name:'zhufeng',
age:10,
//gender:'male'
}
複製代碼
interface Person{
name:string;
age:number;
gender?:'male'|'female';
}
//type Readonly<T> = { readonly [P in keyof T]: T[P] };
let p:Readonly<Person> = {
name:'zhufeng',
age:10,
gender:'male'
}
p.age = 11;
複製代碼
interface Animal {
name: string;
age: number;
}
/**
* From T pick a set of properties K
* type Pick<T, K extends keyof T> = { [P in K]: T[P] };
*/
// 摘取 Animal 中的 name 屬性
type AnimalSub = Pick<Animal, "name">; //{ name: string; }
let a:AnimalSub = {
name:'zhufeng',
age:10
}
複製代碼
readonly
或 ?
修飾符在一個映射類型裏能夠用前綴 +
或-
來表示這個修飾符應該被添加或移除interface Fish {
name: string
}
interface Water {
name: string
}
interface Bird {
name: string
}
interface Sky {
name: string
}
//三元運算符
type Condition<T> = T extends Fish ? Water : Sky;
let condition: Condition<Fish> = { name: '水' };
複製代碼
interface Fish {
fish: string
}
interface Water {
water: string
}
interface Bird {
bird: string
}
interface Sky {
sky: string
}
type Condition<T> = T extends Fish ? Water : Sky;
//(Fish extends Fish ? Water : Sky) | (Bird extends Fish ? Water : Sky)
// Water|Sky
let condition1: Condition<Fish | Bird> = { water: '水' };
let condition2: Condition<Fish | Bird> = { sky: '天空' };
複製代碼
type E = Exclude<string|number,string>;
let e:E = 10;
複製代碼
type E = Extract<string|number,string>;
let e:E = '1';
複製代碼
type E = NonNullable<string|number|null|undefined>;
let e:E = null;
複製代碼
`
js function getUserInfo() { return { name: "zhufeng", age: 10 }; }// 經過 ReturnType 將 getUserInfo 的返回值類型賦給了 UserInfo type UserInfo = ReturnType;react
const userA: UserInfo = { name: "zhufeng", age: 10 };jquery
##### 10.7.3.5 InstanceType<T>
- 獲取構造函數類型的實例類型
```js
class Person{
name:string;
constructor(name){
this.name = name;
}
getName(){console.log(this.name)}
}
type P = InstanceType<typeof Person>;
let p:P = {name:'zhufeng',getName(){}};
複製代碼
declare const $:(selector:string)=>{ //變量
click():void;
width(length:number):void;
};
declare let name:string; //變量
declare let age:number; //變量
declare function getName():string; //方法
declare class Animal{name:string} //類
interface Person{ //聲明接口
name:string
}
type Student = { //聲明類型
name:string
}|'string';
複製代碼
declare enum
定義的枚舉類型declare enum Seasons {
Spring,
Summer,
Autumn,
Winter
}
let seasons = [
Seasons.Spring,
Seasons.Summer,
Seasons.Autumn,
Seasons.Winter
];
複製代碼
declare 定義的類型只會用於編譯時的檢查,編譯結果中會被刪除。上例的編譯結果以下webpack
var seasons = [
Seasons.Spring,
Seasons.Summer,
Seasons.Autumn,
Seasons.Winter
];
複製代碼
也能夠同時使用declare
和 const
git
declare const enum Seasons {
Spring,
Summer,
Autumn,
Winter
}
let seasons = [
Seasons.Spring,
Seasons.Summer,
Seasons.Autumn,
Seasons.Winter
];
複製代碼
編譯結果github
var seasons = [
0 /* Spring */,
1 /* Summer */,
2 /* Autumn */,
3 /* Winter */
];
複製代碼
namespace
表示一個全局變量包含不少子屬性declare namespace ${
function ajax(url:string,settings:any):void;
let name:string;
namespace fn {
function extend(object:any):void;
}
}
$.ajax('/api/users',{});
$.fn.extend({
log:function(message:any){
console.log(message);
}
});
export {};
複製代碼
*.d.ts
typings\jquery.d.tsweb
declare const $:(selector:string)=>{
click():void;
width(length:number):void;
}
複製代碼
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2015",
"outDir":"lib"
},
"include": [
"src/**/*",
"typings/**/*"
]
}
複製代碼
$('#button').click();
$('#button').width(100);
export {};
複製代碼
//對於common.js風格的模塊必須使用 import * as
import * as jQuery from 'jquery';
jQuery.ajax('/user/1');
複製代碼
cnpm i @types/jquery -S
複製代碼
types\jquery\index.d.ts
declare function jQuery(selector:string):HTMLElement;
declare namespace jQuery{
function ajax(url:string):void
}
export default jQuery;
複製代碼
tsconfig.json
paths
,那麼在引入包的的時候會自動去paths
目錄裏找類型聲明文件tsconfig.json
中,咱們一樣也能夠作路徑的映射compilerOptions
裏的 paths
屬性來配置路徑映射。 tsconfig.json{
"baseUrl": "./",// 使用 paths 屬性的話必需要指定 baseUrl 的值
"paths": {
"*":["types/*"]
}
複製代碼
interface String {
double():string;
}
String.prototype.double = function(){
return this+'+'+this;
}
console.log('hello'.double());
interface Window{
myname:string
}
console.log(window.myname);
//export {}
複製代碼
types\global\index.d.ts
declare global{
interface String {
double():string;
}
interface Window{
myname:string
}
}
export {}
複製代碼
"include": [
"src/**/*",
"types/**/*"
]
複製代碼
關鍵字 | 做爲類型使用 | 做爲值使用 |
---|---|---|
class | yes | yes |
enum | yes | yes |
interface | yes | no |
type | yes | no |
function | no | yes |
var,let,const | no | yes |
class Person{
name:string=''
}
let p1:Person;//做爲類型使用
let p2 = new Person();//做爲值使用
interface Animal{
name:string
}
let a1:Animal;
let a2 = Animal;//接口類型不能用做值
複製代碼
use.js
interface Animal{
name:string
}
let a1:Animal={name:'zhufeng',age:10};
console.log(a1.name);
console.log(a1.age);
複製代碼
types\animal\index.d.ts
interface Animal{
age:number
}
複製代碼
class Form {
username: Form.Item='';
password: Form.Item='';
}
//Item爲Form的內部類
namespace Form {
export class Item {}
}
let item:Form.Item = new Form.Item();
console.log(item);
複製代碼
namespace
來擴展函數function greeting(name: string): string {
return greeting.words+name;
}
namespace greeting {
export let words = "Hello,";
}
console.log(greeting('zhufeng'))
複製代碼
enum Color {
red = 1,
yellow = 2,
blue = 3
}
namespace Color {
export const green=4;
export const purple=5;
}
console.log(Color.green)
複製代碼
{
"compilerOptions": {
"declaration": true, /* Generates corresponding '.d.ts' file.*/
}
}複製代碼