2017-09-22 8 views
1

私は、オブジェクトのキーの型(インタフェース)を定義する構文を理解しようとしています。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 
     }))() 
} 

答えて

2

それはあなたが求めているものを本当にはっきりしていない:あなたはPatentの定義にreportプロパティのタイプを定義します。したがって:

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

ので、その場合、余分な属性は問題にはなりません。

+0

正確に私が必要としたもの。どうもありがとうございました。 –

関連する問題