TypeScript:依赖于另一个接口属性

问题描述 投票:0回答:1

是否可以键入依赖于另一个接口属性的接口属性?

例如我有:

const object = {
  foo: 'hello',
  bar: { hello: '123', },
}

我想确保 bar 的键必须是 foo 的值。

interface ObjectType = {
  foo: string;
  bar: { hello: string; } // instead of hardcoding have something like this? --> payload: { ValueOfFoo: string; }
}

谢谢! :)

javascript reactjs angular typescript react-redux
1个回答
7
投票

您需要一个泛型来捕获特定字符串的类型

interface ObjectType<K extends string> {
    foo: K;
    bar: { [P in K]: string };
}

然后就可以写了

const object: ObjectType<'hello'> = {
    foo: 'hello',
    bar: { hello: '123', },
};

或者,如果您有一个接受此类对象的函数,您可以使用该接口通过完整类型推断来强制执行规则

function useObject<K extends string>(o: ObjectType<K>) { }

useObject({
    foo: 'hello', 
    bar: { hello: '113' } // works
});

useObject({
    foo: 'hello', 
    bar: { world: '113' }
//         ^^^^^−−−−−−−−−−−− error, `world` should be `hello`
});

游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.