【发布时间】:2021-08-05 16:23:34
【问题描述】:
我试图在编译时将某些字符串字段限制为仅具有某些值。问题是这些值应该是可扩展的。 这是一个简化的示例:
type Foobar = 'FOO' | 'BAR';
interface SomeInterface<T extends Foobar> {
amember: T;
[key: string]: string; // this really has to stay
}
// let's test it
const yes = {
amember: 'FOO'
} as SomeInterface<'FOO'>; // compiles as expected
// const no = {
// amember: 'BAZ'
// } as SomeInterface<'BAZ'>; // Type '"BAZ"' does not satisfy the constraint 'Foobar' as expected
// so far so good
// Now the problem
abstract class SomeClass<T extends Foobar> {
private anotherMember: SomeInterface<T>;
}
type Foobarbaz = Foobar | 'BAZ';
class FinalClass extends SomeClass<Foobarbaz> { //no good anymore
}
错误是
类型“Foobarbaz”不满足约束“Foobar”。类型 '"BAZ"' 不能分配给类型 'Foobar'。
所以问题是:如何在打字稿中将“类型”限制为仅属于某些字符串,但是否可以使用其他字符串进行扩展? 还是这是一个 XY 问题并且有明显更好的解决方案?
Typescript 2.3.4 但我认为如果那里有魔法我可以升级到 2.4。
【问题讨论】:
标签: typescript alias