英文:
How to use ReturnType on a function that also has a generic
问题
以下是您要翻译的内容:
这段代码片段演示了问题:
function foo<T>(init: T) {
let data = init;
return {
getData: () => data,
update: (u: T) => { data = u }
}
}
let obj: ReturnType<typeof foo>;
obj = foo<boolean>(true); // 错误
错误信息如下:
类型 '{ getData: () => boolean; update: (u: boolean) => void; }' 不能分配给类型 '{ getData: () => unknown; update: (u: unknown) => void; }'。
属性 'update' 的类型不兼容。
类型 '(u: boolean) => void' 不能分配给类型 '(u: unknown) => void'。
参数 'u' 和 'u' 的类型不兼容。
类型 'unknown' 不能分配给类型 'boolean'。
问题出在以下代码中:
let obj: ReturnType<typeof foo>;
我没有定义泛型,这导致 T
变成了 unknown
。您可以按照以下方式修复:
let obj: ReturnType<typeof foo>;
obj = foo<unknown>(true);
所以我的问题是,是否可能在以下代码中以某种方式定义泛型 T
并将其设置为布尔值,例如:
let obj: ReturnType<typeof foo>;
英文:
The following code snippet demonstrates the problem:
function foo<T>(init: T) {
let data = init;
return {
getData: () => data,
update: (u: T) => { data = u }
}
}
let obj: ReturnType<typeof foo>;
obj = foo<boolean>(true); // ERROR
The error is:
Type '{ getData: () => boolean; update: (u: boolean) => void; }' is not assignable to type '{ getData: () => unknown; update: (u: unknown) => void; }'.
Types of property 'update' are incompatible.
Type '(u: boolean) => void' is not assignable to type '(u: unknown) => void'.
Types of parameters 'u' and 'u' are incompatible.
Type 'unknown' is not assignable to type 'boolean'.
What happens is that in
let obj: ReturnType<typeof foo>;
I don't the define the generic, which makes T
-> unknown
. So I can fix this as follows
let obj: ReturnType<typeof foo>;
obj = foo<unknown>(true);
So my question is, is it possible to somehow define the generic T in
let obj: ReturnType<typeof foo>;
and set it to, for example, a boolean?
答案1
得分: 1
有一种传递泛型而不调用函数本身的语法:
const func = <T>(arg: T): void => {}
// (arg: boolean) => void
const booleanFunc = func<boolean>
// (arg: string) => void
const stringFunc = func<string>
你可以使用相同的语法获取返回类型:
ReturnType<typeof foo<boolean>>
英文:
There is a syntax for passing a generic without calling the function itself:
const func = <T>(arg: T): void => {}
// (arg: boolean) => void
const booleanFunc = func<boolean>
// (arg: string) => void
const stringFunc = func<string>
You can apply the same syntax to get the return type:
ReturnType<typeof foo<boolean>>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论