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

这个人只是一个例子。 “年龄不足的红色波浪曲”就是我想要完成的(类型安全),而不是我遇到的问题。 –