Skip to content

847 - String Join #850

Open
Open

Description

@uid11
type Tuple = readonly string[];

/**
 * Tail<['1', '2', '3']> = ['2', '3'].
 */
type Tail<T extends Tuple> = T extends readonly [infer Head, ...infer Rest] ? Rest : [];

/**
 * Join<['1', '2'], " - "> = '1 - 2'.
 * Join<['1'], " - "> = '1'.
 * Join<[], 'x'> = ''.
 */
type Join<T extends Tuple, Separator extends string> = T extends readonly []
    ? ''
    : T extends readonly [infer Head]
    ? Head
    : `${T[0]}${Separator}${Join<Tail<T>, Separator>}`;

declare function join<D extends string>(delimiter: D): <P extends Tuple>(...parts: P) => Join<P, D>;

Activity

  1. added
    answer
    en
    on Feb 8, 2021
  2. m-b-davis commented on Feb 9, 2021

    @m-b-davis

    Nice!

  3. earshinov commented on Jun 21, 2021

    @earshinov

    I wonder why changing the condition in Join into

    type Join<T extends Tuple, Separator extends string> = T extends readonly [infer Head]
        ? Head
        : T extends readonly [infer head, ...infer tail]
        ? `${T[0]}${Separator}${Join<Tail<T>, Separator>}`
        : '';

    makes TypeScript complain

    image

    Type 'Tail<T>' does not satisfy the constraint 'Tuple'.
      Type 'unknown[] | []' is not assignable to type 'readonly string[]'.
        Type 'unknown[]' is not assignable to type 'readonly string[]'.
          Type 'Tail<[head, ...tail] & readonly string[]>' is not assignable to type 'readonly string[]'.
            Type 'unknown[] | []' is not assignable to type 'readonly string[]'.
              Type 'unknown[]' is not assignable to type 'readonly string[]'.
                Type 'unknown' is not assignable to type 'string'.
    

    🤔

  4. uid11 commented on Jun 21, 2021

    @uid11
    ContributorAuthor

    Because in this case, TypeScript cannot prove that Tail<T> always returns Tuple.

    This can be fixed by forcing the result of Tail<T> to be a Tuple (TS Playground):

    type Tail<T extends Tuple> = T extends readonly [infer Head, ...infer Rest]
        ? Rest extends Tuple
            ? Rest
            : []
        : readonly [];
    
    type Join<T extends Tuple, Separator extends string> = T extends readonly [infer Head]
        ? Head
        : T extends readonly [infer head, ...infer tail]
        ? `${T[0]}${Separator}${Join<Tail<T>, Separator>}`
        : '';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    847answeren

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions