类型安全的mustache模板

14
有没有一种解决方案,可以让你做以下操作?

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不是Person类型的属性,哈希类型是Person,因此在age下面会出现红色波浪线。最好使用Visual Studio Code中可用的机制。
更新:
明确一下,我想要实现的是Hello {{name}}, {{age}}<!-- age下面有红色波浪线 -->,而不是我遇到的问题。

这个库在提取胡子类型方面尽力而为,与其他响应保持一致:https://github.com/rjz/ts-mustache - rjz
3个回答

1

这并不是一件容易的事情,但是有一些复杂的方法可以实现。我脑海中最简单的方法是创建一个工具,将您的*.mustache模板编译为TypeScript模块,然后您只需像导入常规TypeScript文件一样导入这些模块,而不是像fs.readFileSync那样读取它们。以下是使用年龄模板进行编译的示例结果:

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);
}

这个工具还需要插入到您用于构建应用程序和增量构建监视模式的脚本中。

0

正如Nikita提到的那样,使用Mustache没有任何工具可以完成这个任务,您需要编写一个编译器。如果您愿意放弃Mustache,您可以使用模板字面量

我编写了嵌入式TypeScript,它使用编译器生成类型安全的模板,具有ejs风格的语法。它是开源的,因此您可以使用该代码作为基础来构建类似于Mustache风格的语法的东西。


-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');

这个人只是一个例子。我想要实现的是“年龄下面的红色波浪线”(类型安全),而不是我遇到的问题。 - William Lohan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接