是否有解决方案可以执行以下操作?:
MY-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 -->
是我想要完成的,而不是我遇到的问题。
答案 0 :(得分:0)
没有简单的方法可以做到这一点;然而,有一些复杂的。我想到的最简单的方法是创建一个工具,将您的 *.mustache
模板编译成 typescript 模块,然后您只需将这些模块作为常规 typescript 文件导入,而不是 fs.readFileSync
ing 它们。下面是一个示例,说明您的模板的编译结果可能与年龄有关:
import * as Mustache from 'mustache';
const template = 'Hello {{name}}, {{age}} <!-- red squiggles under age -->';
export interface TemplateParams {
name: string;
age: string;
}
export default function render(params: TemplateParams): string {
return Mustache.render(template, params);
}
此工具还需要插入到您用于构建应用的脚本中,并在监视模式下逐步构建。
答案 1 :(得分:0)
作为 Nikita mentioned,没有任何工具可以使用 Mustache 完成此操作,您需要编写一个编译器。如果您愿意摆脱小胡子,可以使用 template literals。
我编写了 embedded-typescript,它使用编译器生成具有 ejs 启发语法的类型安全模板。它是开源的,因此您可以使用代码作为基础,为受胡子启发的语法构建类似的东西。
答案 2 :(得分:-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');