Búsqueda de sitios web

typescript - literal de cadena de plantilla con variable causa: Argumento de tipo s no asignable al parámetro de tipo


Esta es una pregunta continua con esta pregunta: ¿hay alguna manera de diferenciar una cadena y un literal de cadena de plantilla?

type Data = {
  arrayObject: {
    firstName: string;
    lastName: string;
  }[];
};

type ArrayElementType<A> = A extends readonly (infer T)[] ? T : never

type TupleOf<A extends number, R extends number[] = []> =
  R['length'] extends A ? R : TupleOf<A, [...R, R['length']]>;

type Integers = TupleOf<1>;

type Indexes = Integers[number];

type PathFinder<T, Key extends keyof T = keyof T> = Key extends string
    ? T[Key] extends (string | boolean | number | symbol)[]
      ? `${Key}.${Indexes}`
      : T[Key] extends object[]
        ? `${Key}.${Indexes}.${PathFinder<ArrayElementType<T[Key]>>}`
        : T[Key] extends Record<string, any>
          ? `${Key}.${PathFinder<T[Key]>}`
          : Key
    : never;

function register<Data>(name: PathFinder<Data>) {
  console.log(name)
}

const index = '0'

register(`arrayObject.${index}.lastName` as const); // works for TS 4.1
register(`arrayObject.${index}.lastName`); // works for TS 4.2

const i:number = '0'
register(`arrayObject.${index}.lastName` as const); fail
register(`arrayObject.${index}.lastName`); // fail

sin embargo, cuando el índice es dinámico y el tipo será number, por ejemplo, puede resultar en un for loop, esto rompe el tipo nuevamente. ¿Hay alguna manera de incluir el tipo number o string en el tipo de literal de cadena de plantilla?

Parque infantil

Respuesta #1

Hay un pequeño truco StringNumber.

Solución :

const index = '0';

const lit = `arrayObject.${index}.lastName`;
// const lit: string

const litAsConst = `arrayObject.${index}.lastName` as const;


namespace Orig {
  type Data = {
    arrayObject: {
      firstName: string;
      lastName: string;
    }[];
    firstName: string;
  };

  type ArrayElementType<A> = A extends readonly (infer T)[] ? T : never

  type TupleOf<A extends number, R extends number[] = []> =
    R['length'] extends A ? R : TupleOf<A, [...R, R['length']]>;

  type Integers = TupleOf<1>;

  type Indexes = Integers[number];

  type PathFinder<T, Key extends keyof T = keyof T> = Key extends string
    ? T[Key] extends (string | boolean | number | symbol)[]
    ? `${Key}.${Indexes}`
    : T[Key] extends object[]
    ? `${Key}.${Indexes}.${PathFinder<ArrayElementType<T[Key]>>}`
    : T[Key] extends Record<string, any>
    ? `${Key}.${PathFinder<T[Key]>}`
    : Key
    : never;

  function register<Data>(name: PathFinder<Data>) {
    console.log(name)
  }

  type StringNumber<T extends number> = `${T}` // <---- my solution is here

  const index: StringNumber<0> = '0'
  const result = register<Data>(`arrayObject.${index}.lastName` as const);
  register<Data>('firstName');
}