这是我的代码:
type FormState = "email" | "password" | "whatever";
const f = <
T extends FormState,
K extends keyof T
>(
fieldName: K,
fieldValue: T[K],
hasErrors?: boolean
) => {}
f.bind(null, "email"); // <-- This gives error
我无法改变类型和函数,我怎么能在这里使用绑定?
这是一个到typescript游乐场的链接。
错误日志为:
No overload matches this call.
Overload 1 of 6, '(this: (this: null, arg0: number | ... 42 more ... | "padEnd", fieldValue: string | ... 42 more ... | ((maxLength: number, fillString?: string | undefined) => string), hasErrors?: boolean | undefined) => void, thisArg: null, arg0: number | typeof iterator | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | ... 31 more ... | "padEnd"): (fieldValue: string | ... 42 more ... | ((maxLength: number, fillString?: string | undefined) => string), hasErrors?: boolean | undefined) => void', gave the following error.
Argument of type '"email"' is not assignable to parameter of type 'number | unique symbol | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | ... 28 more ... | "padEnd"'.
Overload 2 of 6, '(this: (this: null, ...args: "email"[]) => void, thisArg: null, ...args: "email"[]): (...args: "email"[]) => void', gave the following error.
The 'this' context of type '<T extends FormState, K extends keyof T>(fieldName: K, fieldValue: T[K], hasErrors?: boolean | undefined) => void' is not assignable to method's 'this' of type '(this: null, ...args: "email"[]) => void'.
Types of parameters 'fieldName' and 'args' are incompatible.
Type '"email"' is not assignable to type 'number | unique symbol | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | ... 28 more ... | "padEnd"'.
K extends keyof T
和T extends FormState
表示K
将得到0
,1
或2
…作为价值。
f
函数看起来像这样:
const f = (fieldName: number, fieldValue: string, hasErrors?: boolean) => {}
// and to bind f you have to bind a number as the second parameter
f.bind(null, 0);
但是,我猜这不是你想要的,我认为你需要的fieldName
是FormState
。请尝试将fieldName
的类型更新为T
,而不是K
const f = <T extends FormState, K extends keyof T>(fieldName: T, fieldValue: T[K], hasErrors?: boolean) => {}
f.bind(null, "email");
看起来你正在使用错误的类型,因为你正在做keyof FormState
和做keyof string
一样,它只是给你字符串方法。也许您应该将函数限制为单个参数或增强类型?
type FormState = "email" | "password" | "whatever";
const f = <T extends FormState>(fieldName: T, hasErrors?: boolean) => {}
f.bind(null, "email");
游乐场