首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法强制sub拥有一个与对象键匹配的字段?

问有没有办法强制sub拥有一个与对象键匹配的字段?
EN

Stack Overflow用户
提问于 2020-04-20 17:28:29
回答 1查看 17关注 0票数 1

我想创建一个类型,其中value必须与对象的键匹配。有没有办法在typescript中做到这一点?

代码语言:javascript
复制
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"},
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-20 17:54:29

我找到了一个解决方案。但看起来并不优雅。

代码语言:javascript
复制
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>) {

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61319143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档