我想创建一个类型,其中value必须与对象的键匹配。有没有办法在typescript中做到这一点?
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"},
}发布于 2020-04-20 17:54:29
我找到了一个解决方案。但看起来并不优雅。
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>) {
}https://stackoverflow.com/questions/61319143
复制相似问题