将HTML导入到Typescript以用作TemplateStringLiteral

Dim*_*rio 10 html typescript

这是我第一次使用typescript,并希望将typescript合并到我的webpack构建中.

我正在使用ts-loader和babel-loader来加载ts文件,现在正试图将html文件加载到脚本中.(Polymer Lit HTML)

import template from './template.html';

render(props) {
    return html([`${template}`]);
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

TS2345: Argument of type 'string[]' is not assignable to parameter of type 'TemplateStringsArray'.
Property 'raw' is missing in type 'string[]'.
Run Code Online (Sandbox Code Playgroud)

不知道怎么解决这个问题?好像我需要将模板转换为TemplateStringsArray,但我基本上不知道该怎么做.

更新1:

我用这样的内容创建html.d.ts文件.

declare module '*.html' {
    const content: string;
    export default content;
}
Run Code Online (Sandbox Code Playgroud)

但似乎模板的值未定义.

html是lit-html的一个函数

export declare const html: (strings: TemplateStringsArray, ...values: any[]) => TemplateResult;
Run Code Online (Sandbox Code Playgroud)

更新2

经过一些修补,下面提供的答案发现返回的值不太正确.现在返回的值是{raw: values}我需要将其更改为[raw: values].

interface TemplateStringsArray extends ReadonlyArray<string> {
    readonly raw: ReadonlyArray<string>;
}
Run Code Online (Sandbox Code Playgroud)

这是来自lit-html的html函数的一部分

export const html = (strings, ...values) => {
    return new TemplateResult(strings, values, 'html', extendedPartCallback)
};
Run Code Online (Sandbox Code Playgroud)

基本上我需要将部分字符串更改为[raw : val]{raw: val}

sci*_*per 6

关于你的错误:

TS2345:“string[]”类型的参数不可分配给“TemplateStringsArray”类型的参数。类型“string[]”中缺少属性“raw”。

您必须像这样包装参数以适应 TemplateStringsArray 接口:

const stringArray = [`${template}`];
return html({raw: stringArray, ...stringArray} as TemplateStringsArray);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以提供所需的raw属性并告诉html()-function 给定的对象是 type TemplateStringsArray


Dim*_*rio 6

正常工作的答案的最终版本是这样的:

const stringArray = [`${template}`] as any;
stringArray.raw = [`${template}`];
return html(stringArray as TemplateStringsArray);
Run Code Online (Sandbox Code Playgroud)