【问题标题】:Typesafe call some function from object of functions类型安全从函数对象调用某些函数
【发布时间】:2020-09-23 15:24:42
【问题描述】:

我想创建一个函数对象(所有函数都有 1 个参数)。 并制作另一个函数,该函数可以类型安全地将来自外部调用的参数传递给对象中的一个函数。

const double = (v: number) => v * v
const concat = (v: string) => v + v

const functions = {
    double, concat
}

const execute = <T extends keyof typeof functions>
    (key: T, param: Parameters<typeof functions[T]>[0]) => {

    functions[key](param) // here i can't match param type to function argument type, and getting an error

}

execute('double', 'str') // here everything is fine i get correct TypeError

TS playground

如何解决?

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    我们可以断言 functions[key] 采用 param 类型的参数,以便 TS 确认函数在运行时始终获得正确的参数类型。

    const double = (v: number) => v * v
    const concat = (v: string) => v + v
    
    const functions = {
        double, concat
    }
    
    
    const execute = <T extends keyof typeof functions>
        (key: T, param: Parameters<typeof functions[T]>[0]) => {
    
        (functions[key] as (v:typeof param)=>typeof param)(param)
    } 
    
    execute('double', 5)
    execute('double', 'ram) // error
    execute('concat', 'ram')
    execute('concat', 5) // error
    

    【讨论】:

    • “确保”是指“断言”。你是在告诉——不是问——编译器。
    • 你为什么这么认为?我们总是确信我们得到了正确的参数类型。它在任何情况下都会破裂吗?
    • @IvanTarasov 不幸的是,没有比这更好的了。我们需要microsoft/TypeScript#13995 和/或microsoft/TypeScript#25879 和/或microsoft/TypeScript#27808 之类的东西,以允许编译器在这里验证安全性。你可以跳过其他环节,但我认为类型断言是最简单的
    • 我明白了,谢谢你们,这对我来说几乎就像 ts-ignore
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多