【问题标题】:How can I just specify the return type for a function and do not specify arguments?如何只指定函数的返回类型而不指定参数?
【发布时间】:2020-03-24 16:00:10
【问题描述】:

这样的代码:

const t = {
    k1: null,
    k2: null,
}
const a = {
    k1: () => null,
    k2: (arg1: number) => null,
}
a.k1()
a.k2()

现在我想对象“a”将由对象“t”中的键控制,我想当我写k3,k4时,“t”上不存在哪个键,到“a”,应该有一个错误

所以我试试这个方法

const t = {
    k1: null,
    k2: null,
}
const a: Record<keyof typeof t, (...args: any[]) => void> = {
    k1: () => null,
    k2: (arg1: number) => null,
}
a.k1()
a.k2()

但是当我调用a.k2时,args没有提示,即使我不输入参数也没有编译器错误。

所以,我写下我的想法:

const t = {
    k1: null,
    k2: null,
}
const a: Record<keyof typeof t, (...args: Parameters<typeof a[keyof typeof t]>) => null> = {
    k1: () => null,
    k2: (arg1: number) => null,
}
a.k1()
a.k2()

但是,编译器出错:

'args' 在它自己的类型注解中被直接或间接引用。

Playground

我最后想要的是:

const t = {
    k1: null,
    k2: null,
}
const a: ????? = {
    k1: () => null,
    k2: (arg1: number) => null,
    k3: ()=>null, // should have an error like, 'k3' does not exist in keyof typeof t
}
a.k1()
a.k2()  // should have an error like, An argument for 'arg1' was not provided.

我不知道类型“??????”应该换成什么。

我可以为“key contorll && arguments Tips”做些什么?或者我怎样才能只指定函数的返回类型而不指定参数?

【问题讨论】:

    标签: typescript generics typescript-typings typescript-generics


    【解决方案1】:

    您不能在类型注释中指定变量的类型,并让编译器从初始化表达式中推断出该变量的详细信息。

    你可以做的是使用一个函数。一个函数既可以从参数推断,又可以根据约束检查这些参数:

    const t = { k1: null, k2: null }
    
    function asFunctions<T>() {
        return function <U extends Record<keyof T, (...args: any[]) => void>>(o: U) {
            return o
        }
    }
    const a = asFunctions<typeof t>()({
        k1: () => null,
        k2: (arg1: number) => null,
    });
    a.k1()
    a.k2() // err now
    

    Playground Link

    【讨论】:

    • 但现在我可以将 k3、k4 添加到 "a",它们不存在于 "t"
    • 我认为这是要求..您可以将其更改为不需要来自 t 的密钥,如下所示:typescriptlang.org/play/#code/…
    • 这是一个要求,我不想将 k3 k4 添加到“t”处不存在的“a”
    • 那里可以看到,我要k3有错误:)typescriptlang.org/play/…
    • @Ztory 很抱歉回复晚了,泛型禁用了多余的属性检查。我们可以像这样重新添加它们:typescriptlang.org/play/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多