Typescript string type that must start with specific characters

As of TypeScript 4.1, you can use a template literal type for this.

type StartsWithPrefix = `prefix${string}`;

This works for type unions as well:

// `abc${string}` | `def${string}`
type UnionExample = `${'abc' | 'def'}${string}`;

// For your example:
type MyPrefixTypes = `${MyStringTypes}${string}`;

const ok: UnionExample="abc123";
const alsoOk: UnionExample="def123";
const notOk: UnionExample="abdxyz";

// Note that a string consisting of just the prefix is allowed
// (because '' is assignable to string so
// `${SomePrefix}${''}` == SomePrefix is valid)
const ok1: MyPrefixTypes="foo"
const ok2: MyPrefixTypes="barxyz"
const ok3: MyPrefixTypes="bazabc"
const notOk1: MyPrefixTypes="quxfoo"

You can even define a helper type:

type WithPrefix<T extends string> = `${T}${string}`;

type StartsWithPrefix = WithPrefix<'prefix'>;
type UnionExample = WithPrefix<'abc' | 'def'>;
type MyPrefixTypes = WithPrefix<MyStringTypes>;

Playground link


Related:

  • typescript template literal as interface key
  • Typescript: allow any property starting with a specific string

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)