如何解决TypeScript:依赖于另一个的接口属性
是否可以键入依赖于另一个的接口属性?
例如,我有:
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; }
}
谢谢! :)
解决方法
您需要一个泛型来捕获特定字符串的类型
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`
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。