2017-09-21 14 views
3

あなたが次のことを行うことができます解決策はあります?:タイプセーフ口ひげテンプレート

私-template.mustache

Hello {{name}}! 

index.ts

import { readFileSync, writeFileSync } from 'fs'; 
import * as Mustache from 'mustache'; 

export interface Person { 
    name: string; 
} 

const hash: Person = { 
    name: 'Jon' 
}; 

const template = readFileSync('my-template.mustache', 'utf-8'); 

// somehow let the IDE know the hash type 
const result = Mustache.render(template, hash); 

writeFileSync('my-template.html', result, 'utf-8'); 

次に、あなたがやった場合:

my-template.mustache

あなたが ageの下に赤い波線を得る
Hello {{name}}, {{age}} <!-- red squiggles under age --> 

のでageは人タイプのプロパティではなく、ハッシュタイプは、です。好ましくは、Visual Studio Codeで動作するメカニズム。

更新:
Hello {{name}}, {{age}} <!-- red squiggles under age -->は私が達成しようとしているものです明確にするためには、ない私がいる問題。

答えて

-1

1つの方法は、インターフェイスを使用する代わりにタイプを宣言することです。型宣言はTraitsとして少し機能します。以下では、任意のJSオブジェクトを新しいプロパティを持つ型にマップすることができますが、指定されたプロパティに間違った型を使用しようとすると失敗します。

import { readFileSync, writeFileSync } from 'fs'; 
import * as Mustache from 'mustache'; 

export interface PersonWithName { 
    name: string; 
} 

export declare type Person = PersonWithName | any; 

const hash: Person = { 
    name: 'Jon' 
}; 

const hashWithAge: Person = { 
    name: 'Jon', 
    age: 10, 
    newAge: 20 
}; 

const template = readFileSync('my-template.mustache', 'utf-8'); 
+0

人は例です。私が抱えている問題ではなく、私が成し遂げようとしている(タイプセーフティー)のは、「時代遅れの赤い波」です。 –

関連する問題