类型安全胡子模板

Wil*_*han 8 templates mustache typescript visual-studio-code

是否有解决方案可以执行以下操作?:

我-template.mustache

Hello {{name}}!
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)

如果你做了:

我-template.mustache

Hello {{name}}, {{age}} <!-- red squiggles under age -->
Run Code Online (Sandbox Code Playgroud)

所以age不是Person类型的属性,哈希类型是Person,所以你得到红色的波浪线age.最好是在Visual Studio Code中工作的机制.

更新:
要明确Hello {{name}}, {{age}} <!-- red squiggles under age -->我正在努力完成的事情,而不是我遇到的问题.

小智 -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');
Run Code Online (Sandbox Code Playgroud)