ES6 Template Literals: How to pass a scope before they are interpreted?

后端 未结 3 373
清酒与你
清酒与你 2021-01-01 04:36

I am starting to use template literals to make a error generator.

I have working code, but I am forced to declare the list of possible errors inside the constr

3条回答
  •  独厮守ぢ
    2021-01-01 05:04

    String literals are evaluated immediately. They cannot be used as templates to be formatted later (Unlike for example Python's format strings that look similar).

    You could do what Leonid Beschastny suggests and use little functions that does the interpolation for you.

    Something like this:

    const error = {
        1001: () => 'No token',
        1002: (args) => `${args[1]}`,
        1003: (args) => `${args[1]} ! ${args[2]}`,
        1004: () => 'Missing data'
    };
    this.error = error[code](arguments);
    

提交回复
热议问题