typescript - 关于接口“扩展”的 TypeScript 问题
问题描述
我正在尝试为查询系统编写过滤器类型。在尝试编写getItem(id)
方法时,我偶然发现了这一点,我不知道为什么 Typescript 不允许这样做。
在里面我有一个函数类型,<Type extends BaseType>
它不允许我使用该属性运行查询,不管它将扩展并拥有该属性id
的事实。Type
BaseType
id
该f<T>
部分将抛出此错误:
Argument of type '{ a: { eq: "123"; }; }' is not assignable to parameter of type 'Partial<TypePropertyFilter<T>>'.ts(2345)
/**
* This setup should support "queries" like:
* { id: { eq: "abc"}, someVal: { lt: 5 }}
*/
export type FilterName = 'eq' // | 'lt' | 'gt // etc...
export type FilterRecord<Type> = Record<FilterName, Type | Type[]>
export type TypePropertyFilter<Type extends {}> = {
[P in keyof Type]: Partial<FilterRecord<Type[P]>>
}
export type Filter<Type> = Partial<TypePropertyFilter<Type>>
interface BaseType { a: string, b: number }
interface TestType extends BaseType {
test: boolean
}
const t: TestType = { id: "123", test: "pitr"} as any
const f = <T>(f: Filter<T>) => null
const r = <T extends BaseType>() => {
f<TestType>({
a: {eq: "123"}, // correct (fails with other type)
b: { eq: 4555 }, // correct (fails with other type)
test: { eq: true } // correct (fails with other type)
})
f<BaseType>({
a: {eq: "123"}, // correct (fails with other type)
b: { eq: 4555 }, // correct (fails with other type)
// test: { eq: true } // correctly fails, not of BaseType
})
f<T>({
a: {eq: "123"}, // fails but should succeed, T extends BaseType and should at least support all that f<NodeType> does
})
}
解决方案
我认为问题在于T
inT extends BaseType
可能是一种类型,例如
{
a: "foo" | "bar";
b: number;
}
在这种情况下,您的过滤器{ a: {eq: "123"} }
将不安全
推荐阅读
- java - 我可以在 Java 中控制 JNI 本机方法调用名称吗?
- http - 分块传输编码、内容长度和字节服务
- python - 是否有一种执行命令的方法,然后在不终止命令的情况下继续程序
- google-sheets - 在谷歌表格中执行 REGEXREPLACE 时保留单元格的超链接
- javascript - SvelteKit:500:模块“流”已被外部化以实现浏览器兼容性
- arrays - 使用 Groovy 的简单井字游戏(switch 语句中的索引不会更改双数组中的元素)
- c - 存在或不存在等待时 fork 系统调用的控制流程
- reactjs - 如何在 Next JS 中显示本地视频?
- java - Java Spring RestTemplate 从 api 获取 1 个对象
- html - 具有三角形和半透明背景的语音气泡