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

从TypeScript接口中的属性检测重复值,typescript,interface,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中没有表示这种约束的具体类型。相反,您可以使用

有没有办法从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中没有表示这种约束的具体类型。相反,您可以使用和helper函数来生成该类型的值。例如,这是:

const asDistinctProps = <F extends string, B extends string>(
    props: { foo: F, bar: Exclude<B, F> }
) => props;
这就是你想要的方式


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

let z: string = "hello";
asDistinctProps({foo: z, bar: "goodbye"}); // error! 
您根本无法使用
asDistinctProps
,因为
foo
属性只是
string
。在这里:

asDistinctProps({ foo: "hello", bar: z }); // no error!
不会阻止您两次指定相同的值,因为编译器不认为
字符串
“hello”
冲突


因此,有了以上的警告,这是有可能的。实际上,我可能主要在运行时强制执行约束,而不必担心类型系统涉及太多。好吧,希望这会有帮助;祝你好运


谢谢@jcalz的详尽回答!
asDistinctProps({ foo: "hello", bar: z }); // no error!