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

umb*_*987 35 types typechecking typescript

我知道在 TypeScript 中我们可以强制执行特定的字符串,如下所示:

const myStrings = ['foo', 'bar', 'baz'] as const;
type MyStringTypes = typeof myStrings[number];
Run Code Online (Sandbox Code Playgroud)

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

例如,我想创建一个类型 ( MyPrefixTypes),其中包含'prefix1', 'prefix2', ..., 'prefixN',后跟任何其他字符。

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

例子:

const foo: MyPrefixTypes = 'prefix1blablabla'; // OK
const bar: MyPrefixTypes = 'incorrectprefixblablabla'; // NOT OK
Run Code Online (Sandbox Code Playgroud)

che*_*som 68

从 TypeScript 4.1 开始,您可以为此使用模板文字类型。

type StartsWithPrefix = `prefix${string}`;
Run Code Online (Sandbox Code Playgroud)

这也适用于类型联合:

// `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'
Run Code Online (Sandbox Code Playgroud)

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

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

type StartsWithPrefix = WithPrefix<'prefix'>;
type UnionExample = WithPrefix<'abc' | 'def'>;
type MyPrefixTypes = WithPrefix<MyStringTypes>;
Run Code Online (Sandbox Code Playgroud)

游乐场链接


有关的: