我只是在打字稿中坚持了以下lambda函数定义。这可能是一个新手问题。
type P = { id: string }
type F = <T>(x: T) => string
const f: F = (x: P) => x.id
f({ id: 'abc' }
但它一直抱怨以下内容:
类型'(x:P)=>字符串'不能分配给类型'F'。
参数'x'和'x'的类型不兼容。
类型'T'不能分配给类型'P'。
我只是在上下文中说明为什么我需要通用函数。我正在执行验证输入对象的功能,并且该对象的每个路径都可以配置为进行验证,如下所示:
type Option = { path: string; isVerified: <T>(t: T) => boolean }
const verify = (obj: any, options: Option[]): boolean => {
const results = options.map(option => {
const { path, isVerified } = option
return isVerified(obj[path])
})
return results.every(x => x)
}
type A = number
type B = string
const obj = { a: 1 as A, b: 'abc' as B }
verify(obj, [
{ path: 'a', isVerified: (x: A): boolean => x > 0 },
{ path: 'b', isVerified: (x: B): boolean => x.startsWith('a') }
])
感谢第一个答案,它解决了Update #1
中列出的问题。但是,Update #1
实际上是一个简化的问题。在实际情况下,path
类型下的Option
可以是string
或RegExg
,这使得与Paths[K]
对应的代码无效,如下所示:
type Option = { path: string | RegExp; isVerified: <T>(t: T) => boolean }
const verify = (obj: any, options: Option[]): boolean => {
const results = Object.keys(obj).map(k => {
const verifiers = options
.filter(opt =>
typeof opt.path === 'string' ? opt.path === k : opt.path.test(k)
)
.map(x => x.isVerified)
return verifiers.every(verify => verify(obj[k]))
})
return results.every(x => x)
}
type A = number
type B = string
const obj = { a: 1 as A, b: 'abc' as B }
verify(obj, [
{ path: 'a', isVerified: (x: A): boolean => x > 0 },
{ path: /b/, isVerified: (x: B): boolean => x.startsWith('a') }
])
请参阅Play ground link了解更多详细信息。
并且它一直在抱怨以下:
类型'(x:number)=>布尔'不能分配给类型'(t:T)=>布尔'。
参数'x'和't'的类型不兼容。
类型'T'不能分配给类型'数字'。]>
我只是在打字稿中坚持了以下lambda函数定义。这可能是一个新手问题。类型P = {id:字符串}类型F =