2017-09-21 59 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

Hello {{name}}, {{age}} <!-- red squiggles under age --> 

所以age型人和散列類型的屬性是等你拿age下的紅色波浪線。最好是一個可以在Visual Studio Code中工作的機制。

更新:
要清楚Hello {{name}}, {{age}} <!-- red squiggles under age -->是我想要完成的,而不是我遇到的問題。

回答

-1

一種方法是聲明一個類型而不是使用接口。類型聲明功能有點像特質。在下文中,它允許您將任何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

這個人只是一個例子。 「年齡不足的紅色波浪曲」就是我想要完成的(類型安全),而不是我遇到的問題。 –