TypeScript: tags with template templates show an error

I am trying to use an ES5 template tagged literal with typescript, but it looks like the script type does not have full support for This. I have the following code.

class TemplateLiterals { 
    age: number = 24;
    name: 'Luke Skywalker'
    private tag(strings: string[], personExp, ageExp) :string{
        var str0 = strings[0]; // "that "
        var str1 = strings[1]; // " is a "
        var ageStr;
        if (ageExp > 99) {
            ageStr = 'centenarian';
        } else {
            ageStr = 'youngster';
        }
        return str0 + personExp + str1 + ageStr;
    }
    toString() {
        return this.tag `that ${ this.name } is a ${ this.age }`;
    }
}

The toStringtypescript method shows me the following error.

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

I do not know why this showed me this error. According to mozilla's document, "The first argument to a tag function contains an array of string values." Therefore, it must accept an array of strings. But the actual expectation is TemplateStringsArray. You donโ€™t know how and when it is determined interface TemplateSringsArray. I am currently using type TemplateSringsArrayto avoid this error. Can anyone explain what is happening. Thank you Here is a playground .

+6
2

, . , -. :

ES2015 , , raw ( ). TypeScript TemplateStringsArray.

, TemplateStringsArray , , :

function myTemplateTag(strs: string[]) {
    // ... 
} 

TypeScript 2.0 readonly , . , TemplateStringsArray [].

:

TemplateStringsArray ( ReadonlyArray<string>).

+4

TemplateStringsArray - , TemplateStringsArray, string[] ( ), , ,

class TemplateLiterals { 
    age: number = 24;
    name: string = 'Luke Skywalker'
    private tag(strings: TemplateStringsArray, personExp, ageExp) :string{
        var str0 = strings[0]; // "that "
        var str1 = strings[1]; // " is a "
        var ageStr;
        if (ageExp > 99) {
            ageStr = 'centenarian';
        } else {
            ageStr = 'youngster';
        }
        return str0 + personExp + str1 + ageStr;
    }
    toString() {
        return this.tag `that ${ this.name } is a ${ this.age }`;
    }
}

var luke: TemplateLiterals = new TemplateLiterals()
console.log(luke.toString())
+1

Source: https://habr.com/ru/post/1015329/


All Articles