展示我想要的东西要比给这篇文章打个标题容易得多:
type Foo = "bar" | "baz";
interface Consistency {
foo: Foo;
fooTemplate: `${Foo} in a template`;
}
// I want this to compile (and it does)
const valid1: Consistency = {
foo: "bar",
fooTemplate: "bar in a template",
}
const valid2: Consistency = {
foo: "baz",
fooTemplate: "baz in a template",
}
// I DON'T want this to compile (and it does)
const invalid1: Consistency = {
foo: "bar",
fooTemplate: "baz in a template",
}
const invalid2: Consistency = {
foo: "baz",
fooTemplate: "bar in a template",
}我尝试将Consistency更改为You can play with this example here.
interface Consistency {
foo: Foo;
fooTemplate: `${foo} in a template`; //lowercase foo
}但这并不能编译。在无效的情况下有可能出现编译器错误吗?
发布于 2021-02-09 06:09:46
您可以使用映射类型并直接将其解包,以获得所有有效子类型的联合类型:
type Consistency = {
[K in Foo]: {
foo: K;
fooTemplate: `${K} in a template`;
}
}[Foo]https://stackoverflow.com/questions/66110035
复制相似问题