打字稿 - 更好的方法来强制执行对象的密钥类型?

时间:2017-09-22 07:35:49

标签: typescript

我正在试图找出定义对象密钥的类型(接口)的语法。

无法在StackOverflow或其他任何地方找到如何操作。

我制作了这个方法,它有效,但我发现它很笨拙。是否有任何“官方”语法?

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
        }))()
}

1 个答案:

答案 0 :(得分:2)

您所要求的并不是很清楚:您将在report的定义中定义Patent属性的类型。所以:

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
        }
}

正如您预期的那样为otherKey提供错误。实际错误是:

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'.

但是值得注意的是,你只会得到一个文字值的错误,因为一个简单地实现一个接口的对象可能拥有它想要的任意数量的附加属性,因此额外的属性不会成为问题。那种情况。