Home > Software engineering >  How to create a TypeScript rule based on a presence of a character?
How to create a TypeScript rule based on a presence of a character?

Time:08-12

The context is this change in Roarr logger.

In short, it says that if the function's first parameter is a string and the function has multiple parameters, then the first string must contain % – otherwise, it is an improper invocation, e.g.

const log = <T extends string>(message: T, ...args: number[]) => {};

// valid
log('foo');
log('foo %d', 1);

// invalid
log('foo', 1);

I've seen TypeScript tokenize strings – is it possible to detect if a string literal contains % character?

CodePudding user response:

Using hint from @jcalz I figured out that I am looking for:

type Foo<T extends string> = T extends `${string}%${string}` ? 'FOO' : 'BAR';

type A = Foo<'foo'>; // = 'BAR'
type B = Foo<'foo           
  • Related