gpt4 book ai didi

typescript - 使用泛型基于输入的窄返回类型

转载 作者:行者123 更新时间:2023-12-04 08:06:21 25 4
gpt4 key购买 nike

我正在尝试使用泛型根据输入的特定形状来缩小函数的返回类型。这在 TypeScript 中甚至可能吗?我有以下 MRE 证明了这个问题:

type ValidInput = {
filename: string;
sender: number;
};

type ValidInput2 = {
person: string;
sender: string;
};

type InferSenderType<T extends { sender: any }> = T extends { sender: infer K }
? K
: unknown;

type Api<I extends { sender: any }> = (input: I) => InferSenderType<I>;

declare const loadFile: Api<ValidInput | ValidInput2>;

const a = loadFile({ filename: "q", sender: 3 });

typeof a // string | number

// How do I get it to narrow the return type (in this case 'number') based on the input?

最佳答案

下面是一个例子:

type ValidInput = {
filename: string;
sender: number;
};

type ValidInput2 = {
person: string;
sender: string;
};

type Api = <I extends { sender: any }>(input: I) => I['sender']

declare const loadFile: Api;

const a = loadFile({ filename: "q", sender: 3 });

typeof a // only number
TS Playground

关于typescript - 使用泛型基于输入的窄返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66205700/

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