gpt4 book ai didi

javascript - 根据字符串文字参数为函数输入回调参数

转载 作者:行者123 更新时间:2023-12-03 03:56:02 25 4
gpt4 key购买 nike

我正在尝试输入一些函数,以便在使用该函数时获得正确的类型,在使用时尽量减少显式输入。该函数本质上如下所示,我的目标是根据作为 fntype 参数传递的字符串来输入回调函数的 arg

fn(fntype: string, callback: (arg: any) => void): void;

例如,

fn('foo', (foo) => {
foo.somethingInTheFooInterface;
}

fn('bar', (bar) => {
bar.somethingInTheBarInterface;
}

这些是我想出的类型:

type FooType = "FooType";
const FooType: FooType = 'FooType';

type BarType = 'BarType';
const BarType: BarType = 'BarType';

type ActionTypes = FooType | BarType;

interface Action<T> {
type: T;
}

interface FooInterface extends Action<FooType> {
somethingOnTheFooInterface: string;
}

interface BarInterface extends Action<BarType> {
somethingOnTheBarInterface: string;
}

type CallbackTypes = FooInterface | BarInterface;

type Callback<T extends CallbackTypes> = (action: T) => void;

function fn<T extends CallbackTypes, U extends ActionTypes>(actionType: U, cb: Callback<T>): void;

function fn (actionType, cb) {
cb();
}

当明确使用事物时,它可以正常工作:

// Works fine if we explicitly type the arg
fn(FooType, (arg: FooInterface) => {
arg.somethingOnTheFooInterface
});

// Works fine if we define the generics when calling
fn<FooInterface, FooType>(FooType, arg => {
arg.somethingOnTheFooInterface;
});

但不根据第一个参数输入回调:

// TypeError as arg is typed as the union type CallbackTypes
fn(FooType, arg => {
arg.somethingOnTheFooInterface
})

如果有人可以提供有关如何实现此打字的任何指导,那么我将不胜感激。

最佳答案

如果我理解正确的话,那么这似乎是一个重大的矫枉过正。
您应该能够通过签名重载来实现您的目标:

interface FooInterface {
somethingOnTheFooInterface: string;
}

interface BarInterface {
somethingOnTheBarInterface: string;
}

fn(fntype: "FooType", callback: (arg: FooInterface) => void): void;
fn(fntype: "BarType", callback: (arg: BarInterface) => void): void;
fn(type: string, callback: (arg: any) => void) { ... }

关于javascript - 根据字符串文字参数为函数输入回调参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943693/

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