来自接口的打字稿类型映射

时间:2021-02-12 07:10:45

标签: typescript

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

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,
});

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

1 个答案:

答案 0 :(得分: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,
});