gpt4 book ai didi

javascript - 具有正确签名的通用函数

转载 作者:行者123 更新时间:2023-12-01 01:09:47 24 4
gpt4 key购买 nike

我不知道如何声明函数繁荣的第二个参数以进行正确的类型检查,我的意思是如果有人将函数繁荣的第一个参数发送为“foo1”,那么第二个参数应该只能为: (数字)=>无效。如果“foo2”则(string) => void

interface MyFoo {
foo1: (number) => void;
foo2: (string) => void;
}

class Bar<Foo> {
public boom<T extends Foo, K extends keyof MyFoo>(first: K,
...args: Parameters<T[K] /* here I don't know how to declare this parameter */){

}
}

new Bar<MyFoo>().boom("foo1", /* callback with signature: (number) => void */)

最佳答案

首先,请注意parameter names in function types are required ,因此必须更改此定义:

interface MyFoo {
foo1: (x: number) => void;
foo2: (x: string) => void;
}

现在,在 Bar<Foo>我们只需要一个通用参数 K关于boom()方法,因为类型 Foo将为我们指定。我不完全理解您的用例,因为它看起来也许您想要 boom()接受可变数量的参数,但这与关于如何需要回调函数的注释不匹配。所以我假设boom()接受两个参数:键名和回调函数:

class Bar<Foo> {
public boom<K extends keyof Foo>(first: K, second: Foo[K]) { }
}

然后是如何使用它:

// okay, the callback is (x: number) => void
new Bar<MyFoo>().boom("foo1", (x: number) => console.log(x.toFixed(2)));

// error, the callback is (x: number) => void but should be (x: string) => void
new Bar<MyFoo>().boom("foo2", (x: number) => console.log(x.toFixed(2)));

顺便说一句,这并不会阻止您使用具有非函数属性的接口(interface):

interface MyFoo { age: number }
new Bar<MyFoo>().boom("age", 40); // okay

如果您需要boom()仅适用于与类函数属性相对应的键,您将需要一些更高级的conditional types :

type KeysMatching<T, V> =
Extract<keyof T, { [K in keyof T]: T[K] extends V ? K : never }[keyof T]>;

class Bar<Foo> {
public boom<K extends KeysMatching<Foo, Function>>(first: K, second: Foo[K]) { }
}

// okay, the callback is (x: number) => void
new Bar<MyFoo>().boom("foo1", (x: number) => console.log(x.toFixed(2)));

// error, the callback is (x: number) => void but should be (x: string) => void
new Bar<MyFoo>().boom("foo2", (x: number) => console.log(x.toFixed(2)));

interface MyFoo { age: number }

// error, "age" is not accepted anymore
new Bar<MyFoo>().boom("age", 40); // error

希望对您有帮助。祝你好运!

关于javascript - 具有正确签名的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com