如何解决每个属性带有前缀的映射类型
我想创建一个只允许以给定前缀开头的属性的类型:
const example = {
'#prop1': () => {},'#prop2': () => {}
}
因此,在这种情况下,每个属性都必须以 #
为前缀。我在 »Template Literal Types« 中玩过 »Mapped Types«,如下所示:
interface WithD {
[s: `#${string}`]: () => void
}
但这会产生此错误:
索引签名参数类型必须是“字符串”或“数字”。
有什么办法可以做到吗?
解决方法
就像@Nadia Chibrikova 所说的,如果事先不知道 WithD
的值,就无法构建 example
。
处理它的唯一方法 - 是知道(能够推断)您要验证的类型。
type Validation<T extends Record<string,any>> = {
[Prop in keyof T]: Prop extends `#${string}` ? T[Prop] : never
}
type Assert<T,U> = T extends U ? U extends T ? true : false : false
const example1 = {
'#prop1': () => { },'#prop2': () => { },}
const example2 = {
...example1,'prop3': () => { }
}
type Example1 = typeof example1;
type Example2 = typeof example2;
type Result1 = Assert<Example1,Validation<Example1>> // true
type Result2 = Assert<Example2,Validation<Example2>> // false
const isValid = <T extends Validation<T>>(arg: T) => { }
isValid(example1) // ok
isValid(example2) // expected error
因此,TS 应该根据函数参数或类型泛型参数推断您的类型
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。