Home > front end >  Why can’t back ticks be used to extract type defination in Typescript
Why can’t back ticks be used to extract type defination in Typescript

Time:06-29

I ran in to the following situation and I couldn't find the possible reason the caused error (TS1005: ']' expected.).

interface IconProps0 {
    size: string,
    type: string
}

interface IconProps {
    iconType?: IconProps0[`type`]; // use backtick - TS1005: ']' expected.
    iconSize?: IconProps0['size']; // use single quote
}

It works fine with TypeScript version 4.6 but version 3.9 throws the error. Can the older version of TypeScript just fail to understand the syntax?

Edit

Add the minimal reproducible example

CodePudding user response:

Template literal types of the form `foo${Bar}` were introduced in TypeScript 4.1 and cannot be used in earlier versions. They are useful for string interpolation / substitution / manipulation at the type level, and are overkill for just plain string literals.

On the other hand, string literal types of the form "baz" or 'baz' were introduced in TypeScript 1.8. Unless you need to manipulate strings at the type level, you should probably just use these.

  • Related