Friday, June 15, 2018

Importing HTML to Typescript to use as TemplateStringLiteral

Leave a Comment

Basically 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. Any suggestion will be awesome.

Thanks

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; 

1 Answers

Answers 1

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment