我想创建一个值必须与对象键匹配的类型。有没有办法在打字稿中做到这一点?
type Foo = {
[key: string]: {
target: keyof Foo
}
};
const foo: Foo = {
a: {target: "b"},
b: {target: "c"},
c: {target: "b"},
}
const goo: Foo = {
a: {target: "any value"}, // I want this to show an error
b: {target: "c"},
c: {target: "b"},
}
答案 0 :(得分:0)
我找到了解决方案。但是看起来并不优雅。
type Goo<T> = { target: T };
type Foo<K extends string, T extends K> = {[k in K]: Goo<T>};
F({
a: {target: "a"},
g: {target: "a"}
});
function F<K extends string, T extends K>(foo: Foo<K, T>) {
}