简体   繁体   English

Typescript-实施对象键类型的更好方法?

[英]Typescript - Better way to enforce an object's key type?

I'm trying to figure out the syntax to define a type (interface) of an object's key. 我试图找出语法来定义对象键的类型(接口)。

Couldn't find how to do it on StackOverflow or anywhere else. 在StackOverflow或其他任何地方都找不到方法。

I have crafted this method, it works but I find it clumsy. 我已经设计了这种方法,它可以工作,但是我发现它笨拙。 Is there any "official" syntax for it? 是否有任何“官方”语法?

interface Report {
    action: string;
    exists?: boolean;
    warnings? : string[];
    errors? : string[];
}

let patent: Patent = {
        numbers: { … },
        dates : { … },
        report: ( ():Report => ({ // This works, it enforces the key's type but looks ugly
            action : "create",
            exists : false,
            otherKey : "otherValue" // Typescript detects this wrong key, that's good
        }))()
}

It's not really clear what you're asking: you would define the type of the report property in the definition of Patent . 目前还不清楚您要问什么:您可以在Patent的定义中定义report属性的类型。 So: 所以:

interface Report {
    action: string;
    exists?: boolean;
    warnings? : string[];
    errors? : string[];
}

class Patent {
  numbers: any;
  dates: any;
  report: Report;
}

let patent: Patent = {
        numbers: { },
        dates : { },
        report: {
            action : "create",
            exists : false,
            otherKey : "otherValue" // Typescript detects this wrong key, that's good
        }
}

gives you an error for otherKey just as you might have expected. 就像您期望的那样,会给您otherKey错误。 The actual error is: 实际错误是:

error TS2322: Type '{ numbers: {}; dates: {}; report: { action: string; exists: false; otherKey: string; }; }' is not assignable to type 'Patent'.
  Types of property 'report' are incompatible.
    Type '{ action: string; exists: false; otherKey: string; }' is not assignable to type 'Report'.
      Object literal may only specify known properties, and 'otherKey' does not exist in type 'Report'.

However it is worth noting that you'll only get that error for a literal value, as an object that simply implements an interface may have as many additional attributes as it wants, so the extra attributes wouldn't be a problem in that case. 但是,值得注意的是,对于文字值,您只会收到该错误,因为仅实现接口的对象可能具有所需的任意多个附加属性,因此在那种情况下,附加属性将不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM