使用打字稿接口验证属性的重复值

时间:2020-03-30 07:28:46

标签: typescript

无论如何,打字稿中是否有验证接口对象属性仅采用唯一值的方法?

示例:

interface MyElement{
   id: number
}

let element1 : MyElement = {
   id: 100
}

let element2 : MyElement = {
   id: 100  //here i would like typescript to show an error saying duplicate ID at compile time
}

因为element1和element2都使用相同的接口“ MyElement”,所以我认为我们可以对MyElement本身进行一些检查。 我是打字稿新手,任何线索都对我有帮助。

1 个答案:

答案 0 :(得分:1)

尽管TypeScript编译器可以检查文字值,但这样做的能力受到限制。您无法使其验证子字符串,因此它无法帮助您检查test1字符串中的$text1.text部分。

尽管如此,仍然可以借助mapped types来限制某些字段的值,例如innerText。您只需要让TSC知道您的某些值实际上是类型。因此,建议是让TSC知道您的ID,并使其成为一种类型。

这意味着从id中删除MyElement字段,引入单一类型,目的是将所有唯一元素保留在应用程序中。由于值格式更改,因此在innerText字段上运行的代码也需要进行修改。

class Elements {
    text1: MyElement = {
        type: 'textinput'
    };

    theNicestSpan: MyElement = {
        type: 'span',
        innerText: 'text1'
    };
}

// This is how you turn a set of properties into a type.
// This means that variables of type ElementID may only have values
// which are names of fields in the Elements class.
type ElementID = keyof Elements;

// Enumerating possible element types as well to get compile-time checks for those as well.
type ElementType = 'textinput'|'span';

class MyElement {
    type: ElementType
    innerText?: ElementID // innerText can only be either 'text1' or 'theNicestSpan'
}

const elements = new Elements;
elements.theNicestSpan; // Use your elements...

另一种可能的方法是只枚举可能的ID值:

type ElementID = 'text1'|'theNicestSpan';

但这对我来说似乎不如将它们存储在集合类中那么灵活。