【发布时间】:2021-05-25 04:21:16
【问题描述】:
是否可以从具有相同参数和泛型但没有返回类型的现有打字稿函数创建新的函数类型?
示例:
我正在尝试从ReturnSame 函数创建类型ReturnNothing,而无需手动定义它。
type ReturnSame = <T extends string>(a: T) => T
type ReturnNothing = <T extends string>(a: T) => void
尝试:
function returnSame<T extends string>(a: T): T {
return a;
}
// Attempt 1: Does not work. Generics is not following to new type.
const returnNothing1 = (...params: Parameters<typeof returnSame>) => {
console.log(params);
};
// Attempt 2: Does not work. Return type is forced.
const returnNothing2: typeof returnSame = (...params) => {
console.log(params);
};
// Attempt 3: Does not work. OmitReturn is a made up Typescript utility.
const returnNothing3: OmitReturn<typeof returnSame> = (...params) => {
console.log(params);
};
// Usage
const same = returnSame<"a">("a");
const nothing1 = returnNothing1<"b">("b");
【问题讨论】:
标签: typescript generics typescript-typings typescript-generics