Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing HTML to Typescript to use as TemplateStringLiteral

This is my first time using typescript, and want to incorporate typescript into my webpack build.

I'm using ts-loader and babel-loader to load the ts files and right now trying to load html file into the script. (Polymer Lit HTML)

import template from './template.html';

render(props) {
    return html([`${template}`]);
}

And here's the error that I got

TS2345: Argument of type 'string[]' is not assignable to parameter of type 'TemplateStringsArray'.
Property 'raw' is missing in type 'string[]'.

Any idea how to solve this? Seems like I need to convert the template into TemplateStringsArray but I basically didn't know what to do.

Update 1:

I create html.d.ts file with content like this.

declare module '*.html' {
    const content: string;
    export default content;
}

But it seems like template have a value of undefined.

html is a function from lit-html

export declare const html: (strings: TemplateStringsArray, ...values: any[]) => TemplateResult;

Update 2

After some tinkering with the answer provided below found out that the returned values is not quite right. The returned value right now is {raw: values} however I need to change it to [raw: values].

interface TemplateStringsArray extends ReadonlyArray<string> {
    readonly raw: ReadonlyArray<string>;
}

This is the part of html function from lit-html

export const html = (strings, ...values) => {
    return new TemplateResult(strings, values, 'html', extendedPartCallback)
};

Basically I need that part of strings is changed to [raw : val] not {raw: val}

like image 994
Dimas Satrio Avatar asked Jun 05 '18 18:06

Dimas Satrio


2 Answers

Regarding to your error:

TS2345: Argument of type 'string[]' is not assignable to parameter of type 'TemplateStringsArray'. Property 'raw' is missing in type 'string[]'.

You have to wrap the parameter to fit the TemplateStringsArray interface like this:

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

This way you provide the needed raw property and tell the html()-function that the given object is of type TemplateStringsArray.

like image 74
scipper Avatar answered Nov 16 '22 14:11

scipper


The final version of the answer that working properly is like this :

const stringArray = [`${template}`] as any;
stringArray.raw = [`${template}`];
return html(stringArray as TemplateStringsArray);
like image 4
Dimas Satrio Avatar answered Nov 16 '22 15:11

Dimas Satrio