以下のコードのように大部分のプロパティが同じで一部のみ異なるオブジェクト間で
変換処理を行いたいと考えております。
interface Base { a: number b: string dontUse: string } interface Convert { a: number b: string c: string } let base: Base = { a: 1, b: '2', dontUse: 'DontUse' } delete base.dontUse; let convert: Convert { // <-- error発生箇所 ...base, c: 'sample', } console.log(convert);
上記コードは変換したjsは想定通りに動きますがTypeScriptとしては以下のようなエラーが出ます。
Type '{ c: string; a: number; b: string; dontUse: string; }' is not assignable to type 'Convert'. Object literal may only specify known properties, and 'dontUse' does not exist in type 'Convert'.
今回は簡易版ですが、a,bのようなメンバが大量にあるのでできるだけ上記のような書き方をしたいのですが
良い方法はないでしょうか?
型キャストで無理矢理な変換ですとBaseやConvertに変更があった場合に、コンパイルエラーにならないため
それは避けたいと考えています。
イメージですが以下のようなコードが書けると一番嬉しいんです。
interface Base { a: number b: string dontUse: string } type Convert = { [P in keyof Base]: Base[P]; // want to delete from keyof Base 'dontUse' and add 'c' c: string; dontUse: undefined; } let base: Base = { a: 1, b: '2', dontUse: 'DontUse' } delete base.dontUse; let convert: Convert = { ...base, c: 'sample', } console.log(convert);
keyof
でBaseのプロパティが取れるので、それに対してc
を追加し dontUse
を削除できれば一番綺麗だと思われます。
尚サンプルコードはこちらにおいています

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/13 13:37