zoukankan      html  css  js  c++  java
  • [TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript

    Conditional types take generics one step further and allow you to test for a specific condition, based on which the final type will be determined. We will look at how they work on a basic level and then leverage their power to allocate function types dynamically based on the type of their parameters, all without any overloads.

    For example, the following code, the 'contianer' type is 'any'

    interface StringContainer { 
        value: string;
        format(): string;
        split(): string[]
    }
    
    interface NumberContainer { 
        value: number;
        neatestPrime: number;
        round(): number;
    }
    
    type Item<T> = {
        id: T,
        container: StringContainer | NumberContainer
    }
    
    let item: Item<string> = {
        id: 'ad',
        container: null
    }
    
    item.container.value;
    item.container.split(); // Compiler error

    Conditional Type can help with this:

    type Item<T> = {
        id: T,
        container: T extends string ? StringContainer : NumberContainer
    }

    We can build 'ArrayFilter' type to only get Array based type:

    type ArrayFilter<T> = T extends any[] ? T : never;
    type StringsOrNumbers = ArrayFilter<string | number | string[] | number[]>

    It filters out 'string, number' type becasue they are not match 'any[]' Array type. And 'never' type is ignored.

    Conditional type can replace function overloads:

    interface Book { 
        id: string;
        tableOfContent: string[];
    }
    
    interface Tv { 
        id: number;
        diagonal: number;
    }
    
    interface IItemService { 
        getItem(id: string): Book;
        getItem(id: number): Tv;
        getItem<T>(id: T): Book | Tv;
    }
    
    let itemService: IItemService;

    We can replace the hightlighted function overloads with contidional types:

    interface IItemService { 
        getItem<T>(id: T): T extends string ? Book: Tv;
    }
  • 相关阅读:
    【Rollo的Python之路】Python 编码与解码
    【Rollo的Python之路】Python 队列 学习笔记 queue
    【Rollo的Python之路】Python 同步条件 学习笔记 Event
    【Rollo的Python之路】Python 条件变量同步 学习笔记 Condition
    【Rollo的Python之路】Python 信号量 学习笔记 Semaphore
    十天冲刺-09
    十天冲刺-08
    十天冲刺-07
    十天冲刺-06
    十天冲刺-05
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10306055.html
Copyright © 2011-2022 走看看