必须以特定字符开头的 Typescript 字符串类型

Typescript string type that must start with specific characters

我知道在 TypeScript 中我们可以像这样强制执行特定的字符串:

const myStrings = ['foo', 'bar', 'baz'] as const;
type MyStringTypes = typeof myStrings[number];

但是,我需要的是仅强制执行最终字符串的第一个字符。

例如,我想用 'prefix1''prefix2'、...、'prefixN' 之类的东西创建一个类型 (MyPrefixTypes),然后是任何其他角色。

使用这个,我可以检查字符串是否正确。

示例:

const foo: MyPrefixTypes = 'prefix1blablabla'; // OK
const bar: MyPrefixTypes = 'incorrectprefixblablabla'; // NOT OK

从 TypeScript 4.1 开始,您可以为此使用 template literal type

type StartsWithPrefix = `prefix${string}`;

这也适用于类型联合:

// `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 of course assignable to string so
// `${SomePrefix}{''}` == SomePrefix is valid)
const ok1: MyPrefixTypes = 'foo'
const ok2: MyPrefixTypes = 'barxyz'
const ok3: MyPrefixTypes = 'bazabc'
const notOk1: MyPrefixTypes = 'quxfoo'

你甚至可以定义一个辅助类型:

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

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

相关:

  • Typescript: allow any property starting with a specific string

Playground link