TypeScript的基础用法

类型

强类型与弱类型(类型安全)

  • 强类型语言层面限制函数的实参类型必须与形参类型相同
  • 弱类型语言层面不会限制实参的类型

静态类型与动态类型(类型检查)

  • 静态类型:
    • 一个变量声明时它的类型就是明确的,之后不可更改
  • 动态类型:
    • 运行阶段才能明确变量类型,变量的类型随时可以改变

JavaScript 是弱类型且动态类型

强类型的优势

  • 错误更早暴露
  • 代码更智能,编码更准确
  • 重构更牢靠
  • 减少不必要的类型判断
Typescript

基本使用

  • 全局安装typescript
npm install typescript -g
  • ts可以完全按照JavaScript标准语法编写代码
const hello = (name: string) => {
    console.log('hello' + name)
}
hello('TypeScript')

在控制台输出命令

tsc .\ts.ts

会编译出来一个js文件

var hello = function (name) {
    return console.log("hello" + name);
};
hello("TypeScript");

以上是使用TS的一个基本用法;

  • 现在我们需要获取到一个TS的配置文件
tsc init

tsconfig.json

{
    "compilerOptions": {
        /* Visit https://aka.ms/tsconfig.json to read more about this file */
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "lib": [ "ES2015","DOM" ],                             /* Specify library files to be included in the compilation. */
        // "allowJs": true,                       /* Allow javascript files to be compiled. */
        // "checkJs": true,                       /* Report errors in .js files. */
        // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        "sourceMap": true,                     /* Generates corresponding '.map' file. */
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
        "outDir": "TypeScript/dist", /* Redirect output structure to the directory. */
        "rootDir": "TypeScript/src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        // "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'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
        /* 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. */
        // "strictNullChecks": true,              /* Enable strict null checks. */
        // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
        /* 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. */
        /* Module Resolution Options */
        // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        // "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. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
        /* Experimental Options */
        // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
        /* Advanced Options */
        "skipLibCheck": true, /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
    }
}

原始数据类型

const a: string = 'aa'
const b: number = 123 // NaN Infinity
const c: boolean = true
const d: void = undefined
const e: null = null
const f: undefined = undefined
// 直接使用会报错,需要添加响应的标准库
const h: Symbol = Symbol()

标准库

  • 需要哪个就引入哪个,以下方式二选一
  • 标准库就是内置对象所对应的声明
"target": "es5", // 对应的声明文件,这里只会引用es5标准库
"lib": ["ES2015","DOM"],  // 只写一个会覆盖所有的标准库,所以需要依次把需要的添加进来

作用域问题

  • 不同文件中相同变量名称的情况,会报出重复定义变量的错误
// const a = 'bbb'

// 解决办法1,立即执行函数
(function () {
    const a = 'bbb'
})()

// 解决办法2
const a = 'ccc'
// 作为一个模块导出,模块是有单独模块作用域的,将模块内的成员变成模块作用域中的局部成员
export { }

Object 类型

  • Object类型泛指 对象,数组,函数
const foo: object = function () { }

// 如果需要普通对象类型
const obj: { name: string, age: number } = { name: 'jack', age: 18 }
// 对象类型限制不能多也不能少
// const obj: { name: string } = { name: 'jack', age: 18 } // 报错

// 确保跟其他示例没有成员冲突
export { }

数组类型

  • 以下两种方式都可以
const arr1: Array<number> = [1, 2, 3]
const arr2: number[] = [1, 2, 3]

function sum(...args: Array<number>) {
    return args.reduce((prev, current) => {
        return prev + current
    }, 0)
}
sum(...arr1)
sum(...arr2)

元祖(tuple)

  • 类型不相符或者长度不同,都会报错
const tuple: [number, string] = [18, 'jack']

枚举(enum)

  • 带有字符串类型的枚举必须在等号后面赋值
enum post {
    title = 'Hello TypeScript',
    num = 0
}
// 纯数字类型的枚举可以不用赋值,只需要写名称即可,值默认是+1的
enum num {
    one,
    two
}

// 数字枚举会在编译后变成一个双向的键值对对象
console.log(post[0]); // num 
console.log(num.one); // 0
console.log(num[0]); // one

const enum num1 {
    one,
    two
}
// 如果不需要用索引访问枚举成员,则可以使用常量枚举
// 索引无法访问到常量枚举
// console.log(num1[0]); // 会在编译时就报错

类(Class)

class Person {
    // 在TS中需要明确在类型中声明所拥有的属性
    name: string
    age: number
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
    }
    say(value: string): void {
        console.log(`my name is ${this.name},${value}`);
    }
}
  • 类的访问修饰符
class Person {
    // 默认就是公有属性
    public name: string
    // 属性“age”为私有属性,只能在类“Person”及其子类中访问。
    private age: number
    // 属性“sex”受保护,只能在类“Person”及其子类中访问。
    protected sex: string
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
        this.sex = 'man'
    }
    say(value: string): void {
        console.log(`my name is ${this.name},${value}`)
    }
}

const jack = new Person('jack', 18)
// 外部只能访问到name属性 say方法
console.log(jack.name) // jack
jack.say('hello world') // my name is jack,hello,world
  • 子类可以访问父类中protected的属性
class Student extends Person {
    constructor(name: string, age: number) {
        super(name, age)

        this.sex
    }
}
  • 如果构造函数前面加上private修饰,那么该类不能被实例化,不能被继承
  • 可以添加一个静态方法来用作实例化
class Student extends Person {
    private constructor(name: string, age: number) {
        super(name, age)
        // 子类可以访问父类中protected的属性
        this.sex
    }
    // 可以添加一个静态方法来用作实例化
    static create(name: string, age: number) {
        return new Student(name, age)
    }
}
// 类“Student”的构造函数是私有的,仅可在类声明中访问。ts(2673)
const tom = new Student('tom', 18) // 报错

const tom = Student.create('tom', 18) // 正常实例化

类和接口

interface Eat {
    // 函数签名的方式
    eat(food: string): void
}
interface Run {
    run(distance: number): void
}
  • implements实现接口
  • 类要实现接口必须要有接口中的成员
  • 约束类之间公共的能力
class Person implements Eat, Run {
    eat(food: string): void {
        console.log(`优雅的吃,${food}`);
    }
    run(distance: number): void {
        console.log(`直立行走,${distance}`);
    }
}

class Animal implements Eat, Run {
    eat(food: string): void {
        console.log(`呼噜呼噜的吃,${food}`);
    }
    run(distance: number): void {
        console.log(`爬行,${distance}`);
    }
}

抽象类(abstract)

  • 抽象类不同于接口,抽象类可以包含具体的实现,而接口只能是成员抽象不能实现
  • 定义为抽象类之后只能被继承,不能使用new实例化
abstract class Animal {
    eat(food: string): void {
        console.log(`呼噜呼噜的吃,${food}`);
    }
    // 抽象方法是函数签名的方法,不能实现,同时子类中必须实现抽象方法
    abstract run(distance: number): void
}

// 子类继承抽象类父类必须要实现抽象方法
class Dog extends Animal {
    run(distance: number): void {
        console.log(`爬行,${distance}`);
    }
}

const dog = new Dog()
dog.eat('骨头') // 呼噜呼噜的吃,骨头
dog.run(100) // 爬行,100

泛型

  • 在定义函数,接口,类的时候没有指定具体类型,在使用的时候才指定具体类型
  • 如果指定具体的值,value参数想要改变类型就需要再定义一次函数很麻烦:如下
function createNumberArray(length: number, value: number): number[] {
    // 使用Array的fill填充数组的值
    const arr = Array<number>(length).fill(value)
    return arr
}
// 只能拿到数字类型的数组
console.log(createNumberArray(3, 100)); // [ 100, 100, 100 ]
  • 把类型变成一个参数,把不明确的类型用T去代表
  • 在函数名后面使用
function createArray<T>(length: number, value: T): Array<T> {
    const arr = Array<T>(length).fill(value)
    return arr
}
console.log(createArray(3, 'ha')); // [ 'ha', 'ha', 'ha' ]
console.log(createArray(3, 10)); // [ 10, 10, 10 ]

基础的TS用法到这里就结束了,方法太多需要在使用中去体会

更多关于TypeScript

讨论数量: 1

下一个Vue项目我要加上ts

4年前

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!