【问题标题】:Typescript type mapping from Interface来自接口的打字稿类型映射
【发布时间】:2021-05-15 22:55:57
【问题描述】:

我正在尝试找出将接口记录值类型映射到正确函数类型的正确方法。

function stringCompose(): string {
    return ''
}
function numberCompose(): number {
    return 0
}

interface Demo {
    stringVal: string;
    numberVal: number;
}
// mapping type something like <T = any> = (() => T)
type ComposeMapper<T = any> = any;

const builder: ComposeMapper<Demo> = ({
    stringVal: stringCompose,
    numberVal: numberCompose,
});

所以想法是,在创建构建器时,它会检查所有接口键是否到位,并且以某种方式还进行值映射,例如接口“字符串”=>需要“()=>字符串”,其中应该填充组合函数。 在我进行类似设置之前,但是有大量的从未检查过,而且解决这些问题的性能真的很差,所以我认为应该有更简单的方法来真正做到这一点。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您似乎需要从界面创建mapped type

    TS Playground link

    function stringCompose(): string {
        return ''
    }
    function numberCompose(): number {
        return 0
    }
    
    interface Demo {
        stringVal: string;
        numberVal: number;
    }
    
    type ComposeMapper<T> = {
        [K in keyof T]: () =>  T[K]
    }
    
    // OK
    const builder: ComposeMapper<Demo> = ({
        stringVal: stringCompose,
        numberVal: numberCompose,
    });
    
    // Error
    const builder1: ComposeMapper<Demo> = ({
    //    ~~~~~~~~ Property 'numberVal' is missing in type '{ stringVal: () => string; }' but required in type 'ComposeMapper<Demo>'.(2741)
        stringVal: stringCompose,
    });
    
    
    // Error
    const builder2: ComposeMapper<Demo> = ({
        stringVal: numberCompose,
    //  ~~~~~~~~~ Type '() => number' is not assignable to type '() => string'.
        numberVal: numberCompose,
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2018-01-18
      • 1970-01-01
      • 2022-12-07
      • 2022-08-17
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多