![](/img/trans.png)
[英]How can I define a type that maps keys to a generic of that key, e.g. Record<K, SomeGeneric<key>>?
[英]Can I define a generic type constraint on DU Keys?
有没有办法定义泛型类型约束,使得
//this will compile
type Contrained = StrongConstraint<"a" | "b" | "c", "a" | "b">
//this wont compile as "a" | "b" | "d" is not a strict subset of "a" | "b" | "c"
type Contrained = StrongConstraint<"a" | "b" | "c", "a" | "b" | "d">
这类似于Exclude
只是更强,因为我不喜欢第二个参数中不属于第一个参数的键。
您可以强制第二个参数扩展第一个:
type ExcludeConstrained<T, U extends T> = Exclude<T, U>
type T1 = ExcludeConstrained<"a" | "b" | "c", "a" | "b">; // OK, T1 = 'c'
type T2 = ExcludeConstrained<"a" | "b" | "c", "a" | "b" | "d">; // ERROR
// -----------------------------------------> ~~~~~~~~~~~~~~~
// Error: Type '"d"' is not assignable to type '"a" | "b" | "c"'
我不认为你的方法是可能的(至少我不知道)。 但是,根据您的用例,您可以检查Partial
。
type StrongConstraint<T> = {
left: T,
right: Partial<T>,
}
// success
const foo: StrongConstraint<'a' | 'b' | 'c'> = {
left: 'a',
right: 'b'
}
// fail
const bar: StrongConstraint<'a' | 'b' | 'c'> = {
left: 'a',
right: 'd'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.