Skip to content

Inconsistent handling of whitespace in string in template literal types #54119

@annacb40

Description

@annacb40

Bug Report

🔎 Search Terms

template literal types
template literal whitespace
template literal spaces
template literal strings

🕗 Version & Regression Information

This changed between versions 4.0.5 and 4.1.5. I think this variety of type definition was not supported prior to 4.1.5.

⏯ Playground Link

Playground link with relevant code

💻 Code

type StringWithNumberX = `${string} ${number}x`;
type CommaSepStringWithNumberX = `${StringWithNumberX}, ${StringWithNumberX}`;
type CommaStringSepStringWithNumberX = `${StringWithNumberX}, ${string}${StringWithNumberX}`;

const commaSepStringWithNumberX: CommaSepStringWithNumberX = 'foo 4x, bar 5x';
const stringWithNumber: StringWithNumberX = 'foo 5x';

const emptyString: StringWithNumberX = ' 5x';
const moreSpacesBetween: StringWithNumberX = 'foo    5x'; // seems consistent given https://github.com/microsoft/TypeScript/issues/46109
const suffixSpaces: StringWithNumberX = 'foo 5   x' // seems consistent given https://github.com/microsoft/TypeScript/issues/46109

// Tabs and new lines are included with string, but spaces are not
const prefixNewLine: StringWithNumberX = '\nfoo 5x'; 
const newLineInString: StringWithNumberX = 'foo\nbar 5x';
const newLineBetween: StringWithNumberX = 'foo \n 5x' 
const suffixNewLine: StringWithNumberX = 'foo 5x\n'; // new line is not ignored
const prefixTab: StringWithNumberX = '\tfoo 5x'; 
const tabInString: StringWithNumberX = 'foo\tbar 5x';
const tabBetween: StringWithNumberX = 'foo \t 5x' 
const suffixTab: StringWithNumberX = 'foo 5x\t'; // tab is not ignored

// Cases that seem inconsistent
const spacesInString: StringWithNumberX = 'foo bar 5x'; // spaces in string are not allowed?
const prefixSpaces: StringWithNumberX = '   foo 5x'; // spaces at start of string are not allowed?

const extraSepSpace: CommaSepStringWithNumberX = 'foo 4x,  bar 5x'; // extra space isn't included with second string?
const extraSepSpace2: CommaStringSepStringWithNumberX = 'foo 4x,  bar 5x'; // adding the string in the separator lets me add exactly one space in between
const twoExtraSepSpace: CommaStringSepStringWithNumberX = 'foo 4x,   bar 5x'; // adding the string in the separator lets me add exactly one space in between

🙁 Actual behavior

${string} in a template literal type will accept tabs and/or new lines anywhere in the string, but does not accept spaces within the string.

🙂 Expected behavior

${string} should allow spaces within the string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions