Dimas Satrio
Dimas Satrio

Reputation: 309

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}

Upvotes: 11

Views: 4208

Answers (2)

Dimas Satrio
Dimas Satrio

Reputation: 309

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

Upvotes: 7

scipper
scipper

Reputation: 3153

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.

Upvotes: 7

Related Questions