从 TypeScript 接口的属性中检测重复值

Detect duplicate values from properties in TypeScript interface

有没有办法检测 TypeScript 接口中属性的重复值?例如:

interface Props {
   foo: string;
   bar: string;
}

let x : Props = {
   foo: 'hello world',
   bar: 'hello world'
} 

// show TypeScript warning for foo and bar having the same value

TypeScript 中没有表示此类约束的具体类型。相反,您可以使用 generic type 和辅助函数来生成该类型的值。例如,像这样:

const asDistinctProps = <F extends string, B extends string>(
    props: { foo: F, bar: Exclude<B, F> }
) => props;

这里,asDistinctProps 是一个通用函数,它接受一个具有 stringfoobar 属性的对象。但是 bar 的类型受到限制,因此它不能与 foo 类型的值相同......只要你处理的是 string literal types 而不仅仅是 string:

let x = asDistinctProps({
    foo: 'hello world',
    bar: 'hello world' // error!
});

let y = asDistinctProps({
    foo: 'hello world',
    bar: 'goodbye cruel world'
}); // okay

这就是你想要的方式。


请记住,编译器通常会将字符串从其文字值扩展为 string,此时无法正确应用约束。这里:

let z: string = "hello";
asDistinctProps({foo: z, bar: "goodbye"}); // error! 

您根本无法使用 asDistinctProps,因为 foo 属性 只是 string。这里:

asDistinctProps({ foo: "hello", bar: z }); // no error!

不会阻止您两次指定相同的值,因为编译器不会将 string 视为与 "hello" 冲突。


所以根据上述警告,这是有可能的。在实践中,我可能主要在运行时强制执行约束,而不用担心类型系统涉及太多。好的,希望有所帮助;祝你好运!

Playground link to code