renamedSignature

tcmts.store.renamedSignature · #t4ze6mp2 · term · runs anywhere

A signature with other names for what it names: renames maps the name a definition was made as (how a signature prints it) to the name to show. Only types and values are renamed, not property or parameter names ({ Foo: Foo } keeps its key), a qualified name's members, or what's in a string literal type.

export function renamedSignature(signature: string, renames: ReadonlyMap<string, string>): string {
  if (!renames.size) return signature;
  return signature.replace(
    /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`|[A-Za-z_$][\w$]*/g,
    (word, at: number) => {
      const to = renames.get(word);
      if (to === undefined) return word;
      const before = signature.slice(0, at).trimEnd().at(-1);
      const after = signature.slice(at + word.length);
      // a member (`{ Foo: …; Bar(): … }`), a parameter (`(Foo: …)`), or a qualified name's member (`ns.Foo`)
      if (
        before === "." ||
        before === "{" ||
        before === ";" ||
        after.startsWith(":") ||
        after.startsWith("?:")
      )
        return word;
      return to;
    },
  );
}

used by