[英]In TypeScript, define a typed function parameters type
Let's declare a generic function:让我们声明一个通用函数:
const fun = <E = any, V = any>(params: { value: V; getValue: (e: E) => V; }) => { /**/ }
In another place, we have a consumer code, which should be typed, and now it causes TS errors:在另外一个地方,我们有一个消费者代码,应该是打出来的,现在却导致了TS错误:
type E = { value: string };
type Params = Parameters<typeof fun>[0];
const run = (params: Params) => {
// expecting params.value to be a string
// TS2339: Property 'length' does not exist on type 'unknown'.
if (params.value.length > 0) {
// TS2345: Argument of type '{ value: unknown; getValue: (e: unknown) => unknown; }'
// is not assignable to parameter of type '{ value: string; getValue: (e: E) => string; }'.
// Types of property 'value' are incompatible.
// Type 'unknown' is not assignable to type 'string'.
fun<E, string>(params);
}
};
Is there a way to get the type of parameters of a typed function?有没有办法获取类型化函数的参数类型? So that Params
was { value: string; getValue: (e: E) => string }
所以Params
是{ value: string; getValue: (e: E) => string }
{ value: string; getValue: (e: E) => string }
. { value: string; getValue: (e: E) => string }
。 Something like Parameters<typeof fun<E,string>>[0]
.像Parameters<typeof fun<E,string>>[0]
这样的东西。
If I understand correctly, you could make the Params
type generic.如果我理解正确,您可以使Params
类型通用。
something like this:是这样的:
const fun = <E = any, V = any>(params: { value: V; getValue: (e: E) => V; }) => { /**/ }
type Params<E> = Parameters<typeof fun<E,string>>[0];
const run = function<E>(params: Params<E>) {
if (params.value.length > 0) {
fun<E, string>(params);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.