TypeScript进阶学习

以下TypeScript内容属于进阶学习,0基础的小伙伴也可以适当的看看
更多学习资源点我获取

1. 函数重载

function hello(name: string): string;
function hello(age: number,): string;
function hello(val: string | number): string{
    if (typeof val === 'string') return '我的名字是' + val
    else if (typeof val === 'number') return '我的年龄是' + val
    else return '非法格式'
}

console.log(hello('皓样'))
console.log(hello(1))

2. 接口继承

interface Parent{
    prop1: string;
    prop2: string;
}

interface Child extends Parent{
    prop3: string;
}

const myObject: Child = {
    prop1: '1',
    prop2: '2',
    prop3: '3'
}

3. 类和抽象类

class Article{
    private title: string;
    protected content: string; // 类中或则子类中访问
    public desc?: string;
    count: number = 100;
    readonly author: string = '只读属性'

    // 存储读取属性
    private _password = ''
    get password(): string{
        return '*****'
    }
    set password(val: string){
        this._password = val
    }

    constructor(title: string, content: string){
        this.title = title
        this.content = content
    }
}

const article = new Article('标题', '内容')
article.password = '1111'

// 抽象类
abstract class Animal{
    abstract name: string;
    abstract maskSound():void;
}

class Cat extends Animal {
    name: string = '小猫'
    maskSound(): void {
        
    }
}

4. 接口继承

interface Animal2{
    name: string;
    get sound(): string;
    maskSound(): void;
}

class Dog implements Animal2{
    get sound(): string {
        throw new Error("Method not implemented.")
    }
    maskSound(): void {
        throw new Error("Method not implemented.")
    }
    name: string = '小狗'
    
}

5. 泛型


//泛型
interface Res {
    code: number,
    message: string,
}


interface Res1 {
    code: number,
    message: string,
    data: string
}

interface Res2 {
    code: number,
    message: string,
    key: string
}
function transData<T extends Res>(res: T) {
    if (res.code === 200) {
        return res.message
    }
    throw new Error('系统错误')
}

transData<Res1>({
    code: 200,
    message: 'succ',
    data: 'ok'
})

transData<Res2>({
    code: 200,
    message: 'succ',
    key: 'ok'
})


// 泛型函数
type Fn1<T> = (a: T) => boolean
type Fn2<T> = (a: string) => T
type Fn3<T, R> = (a: T) => R

const fn1: Fn1<string> = (a) => {
    return true
}

const fn2: Fn2<number> = (a: string) => {
    return 0
}

const fn3: Fn3<number, string> = (a) => {
    return '111'
}

// 泛型接口
interface Product<T = string> {
    name: string;
    price: number;
    other: T
}

const product1: Product<number> = {
    name: '1',
    price: 100,
    other: 100
}

// 默认是string
const product2: Product = {
    name: '1',
    price: 100,
    other: 'aaa'
}

// 泛型类
class MyClass2<T> {
    public value: T;
    constructor(value: T) {
        this.value = value
    }

    do(input: T): T{
        console.log('do ' + this.value)
        return input
    }
}

const myStr2 = new MyClass2<string>('小猫')
myStr.do('name')

// 泛型别名
type MutableArray<T> = T[]
const numbers: MutableArray<number> = [1,2,3,4,5]
const strings: MutableArray<string> = ['a','b']
const arr111: number[] = [1,2,3,4]

6. 基础类型

// 基本数据类型省略
// 联合
const arr: Array<number | string> = [1, 2, '123']
// 元组, 要一一对应
const tuple: [string, number] = ['a', 1]
const arr2:(string|number)[] = [1,2,'123']
// 函数类型
    // 不定义类型写法
    const fun1 = () => false
    // 定义类型写法 类型是  (params: string) => boolean
    const fun2:(params: string) => boolean = () => false
    //或则
    function fun3(params: string): boolean {
        return false;
    }
    //  类型别名
    type Fun = (params: string) => boolean
    const fun4: Fun = () => false;
// 对象类型
    // 方法1
    const obj: object = {
        a: 1,
        b: 2
    }
    // 方法2
    const obj1: {a: string, b: string} = {
        a: '1',
        b: '2'
    }

    // 使用interface 替换类型
    interface Obj {
        a: string,
        b: string
    }
    const obj3: Obj = {
        a: '1',
        b: '2'
    }
// void 类型
const v = (): void => {};
// never 永远不会有返回值
const n1 = (): never => {
    throw new Error()
}
const n2 = (): never => {
    while(true){}
}

7. 枚举类型表驱动发

注意:

  1. 枚举里面值不能是一个function
  2. 常量枚举再编译成js时候不会编译,只有再使用的时候直接转成对应的值,节省代码
  3. 两个枚举不能比较
// 枚举类型 
// 以下是利用表驱动法使用枚举,去掉打量的if语句
enum OrderStatus {
    Pending,
    Canceled,
    Unknown
}
interface Order {
    status: OrderStatus
}

const orderHandlers: Record<number, (order: Order) => void> = {
    [OrderStatus.Pending]: function (order) {

    },
    [OrderStatus.Canceled]: function (order) {

    }
}

function processOrder(order: Order){
    const handler = orderHandlers[order.status] || orderHandlers[OrderStatus.Unknown]
    handler(order)
}

8. 类型对象和类型别名区别

  1. 一个是结构体,一个是别名
  2. interface 可以扩展, type不行
  3. interface 重名会合并, type不能重名
  4. interface可以被类实现, type不能
  5. type支持联合类型和交叉类型,interface不支持
// 定义对象和对象别名
interface User {
    name: string
    age: number
    [propName: string]: any // 可以添加任何属性
}
interface User {
    gender: boolean
}
type UserType = {
    name: string
    age: number
}

// 给User取别名叫UserType1
type UserTyp1 = User

const user1: UserType = {
    age: 20,
    name: '111'
}

// 联合类型(或),可以只定义其中类型的一个
interface Man {
    name: string
}

interface Woman{
    age: number
}
type People = Man | Woman

const p: People = {
    // 联合类型,可以只定义其中类型的一个
    name: '111'
}

// 交叉类型(取交集), 所有属性都要定义出来
type People2 = Man & Woman
const p2: People2 = {
    // 必须两个属性都定义出来
    name: '1111',
    age: 30
}

9. 交叉类型和联合类型

// 交叉
type T6 = {x: number} & {x: string} // x 是never
type T7 = {x: number} & {y: string}  // T7 必须是x 和y都得有
// 联合
type H7 = {x: number} | {x: string} // x是number | string
type H8 = {x: number} | {y: string} // 有x 或则 y 其中一个或则都有

10. 类型保护

// 类型保护,包含 typeof 和 instanceof
const lengthFun = (a: number | string) => {
    // 直接写会报错
    // return a.length
    if (typeof a === 'string') {
        // 加入typeof判断后,a.length 不会报错
        return a.length
    }
    if (typeof a === 'number') {
        return a.toString().length
    }
    return 0;
}

11. 索引类型和映射类似

// 索引类型
interface Product {
    name: string
    price: number
}
// 索引类型
interface Products {
    [id: number]: Product
}

interface ObjStr {
    [key: string]: string
}

let p1: Products = {
    1: {
        name: 'aaa',
        price: 100
    }
}

let objstr: ObjStr = {
    1: 'aaa'
}

// 常见的操作
// 遍历除每个属性
type Keys = keyof Product; // name | price
let keys: Keys = {
    name: 'aa',
    price: 111
};


const product = {
    name: '111'
}
// 映射类型,把对象映射类类型
type Tp = typeof product;
const tp1: Tp = {
    name: 'aaa'
}

12. 条件类型

// 条件类型
// 表达式 
// T extends U ? x : Y
// (A | B) U ? x : Y
type ReType<T> = T extends string ? 1 : 0
type Func<T> = (a: T) => ReType<T>

const testReType: Func<string> = (a) => {
    // 如果T是string, 返回值必须是1
    return 1
}

const testReType2: Func<number> = (a) => {
    // 如果T不是string, 返回值必须是1
    return 0
}

13. 工具类型

// 工具类型

// 1. 把可选转必选
interface Product10 {
    name: string
    price: number
}

// name 和 price 都要定义
const product10: Product10 = {
    name: 'jiang',
    price: 10
}

// 利用Partial可以只定义其中一种, 把属性变成可选
type Par = Partial<Product10>
const par: Par= {
    name: 'jiang'
}

// 2. 把可选转必选
interface Product11 {
    name?: string
    price?: number 
}

type Req = Required<Product11>
// name 和 price必须要赋值
const req: Req = {
    name: 'aaa',
    price: 200
}

// 3. 摘出一些字段
type Pic = Pick<Product10, 'name'>
// pic 只有name
const pic: Pic = {
    name: 'aaaa'
}

// 4. 踢出一些字段
type Omi = Omit<Product10, 'name'>
// omi 只有price
const omi: Omi = {
    price: 200,
}

// 5. 设置只读
type ReadonlyT = Readonly<Product10>

// 6. 去掉null字段
// noNull 只有string
type NoNull = NonNullable<string | null>


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值