1

https://www.typescriptlang.org/play?#code/ATCmA8AcHsCcBdjwJ6VMAogOwMbQCagA8AUCCAMpjjyhb4DOwD8sAllgOYA0Z5ASvCzVa9Ji3ZdgAXmAByOb3LAAMgEMWIuo2asOnGfMV8QAQViw1yLWOABGANoBdQ86Xk2DAGJtYmiKI6AEbQ0AA2oGrCsqwArqB8AHyGVAHaTAAGACQA3hwAZqCwwF4AvrkFRcD8pRkmwAD8wJ4+fohptnEJyiBN2HiERPzc1UIjXiMOAHQz5pbII3ZOI-lqYQygifUgAFwlNjrqLNuNmLgExMOjWOOTM1NzVovLwKvrmyd7-RekPT3DJ2Uj2QDjkES48AAFnIXB0dHZAT0mtkcoIsOUckd4LVEco9ii0RjgaDwZwoTCMVjau4-iAJrjgA4ljTaW8NoitnjgKkaOlVBp4PVkblCblprMLE97E4SXQydCnJSBTiuQShEqWLUgA

It should not have an error here. Is it a ts bug ?

  export type Encode<
    S extends string,
    Rtn extends string = '',
    Last extends string = '',
    Array extends 1[] = [],
    isFirst extends boolean = true
  > = S extends `${infer F}${infer R}`
    ? isFirst extends true
      ? Encode<R, Rtn, F, [...Array, 1], false>
      : F extends Last
      ? Encode<R, Rtn, F, [...Array, 1], false>
      : Encode<
          R,
          Array['length'] extends 1
            ? `${Rtn}${Last}`
            : `${Rtn}${Array['length']}${Last}`,
          F,
          [1],
          false
        >
    : S extends Last
    ? `${Rtn}${[...Array, 1]['length']}${Last}` 
      // error , Type '[...Array, 1]["length"]' is not assignable to type 'string | number | bigint | boolean | null | undefined'
      // but [...Array, 1]['length'] is number
    : `${Rtn}${Last}`
type a1 = Encode<'AAABCCXXXXXXYYY'> // '3AB2C6X3Y'

1 Answer 1

1

For the given type definition:

type a1 = Encode<'AAABCCXXXXXXYYY'>

If the expected type is '3AB2C6X3Y', then the correct type definition of Encode should be:

type Encode<
    S extends string,
    Rtn extends string = '',
    Last extends string = '',
    Array extends 1[] = [],
    isFirst extends boolean = true
  > = S extends `${infer F}${infer R}`
    ? isFirst extends true
      ? Encode<R, Rtn, F, [...Array, 1], false>
      : F extends Last
      ? Encode<R, Rtn, F, [...Array, 1], false>
      : Encode<
          R,
          Array['length'] extends 1
            ? `${Rtn}${Last}`
            : `${Rtn}${Array['length']}${Last}`,
          F,
          [1],
          false
        >
    : S extends Last
    ? `${Rtn}${Last}`
    : `${Rtn}${Array['length']}${Last}`

The compilation error is because typescript is not able to infer the type of [...Array, 1]['length']. You can use another conditional typing ([...Array, 1]['length'] extends 1 ? <> : <>) to tell typescript to treat the value of [...Array, 1]['length'] as a type in the template string. See example.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for sharing , I used [...Array, 1]['length'] extends number ? <> : <> to solve this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.