返回

探索文本片段相似性查询利器:StartWith/EndsWith/PartialByKeys

前端

在类型体操系列的第十六篇中,我们将探索StartWith、EndsWith和PartialByKeys这三个利器,并借助它们来实现文本片段相似性查询。

StartWith:以指定字符串开头

StartWith类型可以确保字符串以指定的子字符串开头,无论子字符串的长度如何。例如:

type StartsWithAB = StartWith<'AB'>;

// 正确
type Test1 = StartsWithAB<'ABC'>;
type Test2 = StartsWithAB<'AB'>;

// 错误
type Test3 = StartsWithAB<'CAB'>;
type Test4 = StartsWithAB<'A'>;

EndsWith:以指定字符串结尾

EndsWith类型与StartWith类型类似,只不过它确保字符串以指定的子字符串结尾。例如:

type EndsWithDE = EndsWith<'DE'>;

// 正确
type Test1 = EndsWithDE<'ABCDE'>;
type Test2 = EndsWithDE<'DE'>;

// 错误
type Test3 = EndsWithDE<'CDE'>;
type Test4 = EndsWithDE<'D'>;

PartialByKeys:根据键值对进行部分匹配

PartialByKeys类型允许我们根据键值对对对象进行部分匹配。例如:

interface User {
  name: string;
  age: number;
  gender: 'male' | 'female';
}

type PartialUser = PartialByKeys<User, 'name' | 'age'>;

// 正确
type Test1 = PartialUser<{ name: 'John', age: 30 }>;

// 错误
type Test2 = PartialUser<{ name: 'John', age: 30, gender: 'male' }>;

应用:文本片段相似性查询

现在,让我们将这三个利器结合起来,实现文本片段相似性查询。具体来说,我们将使用StartWith和EndsWith来检查字符串是否以或结尾于指定的子字符串,使用PartialByKeys来检查字符串是否包含指定的子字符串。

type TextFragmentSimilarity<T extends string> = StartWith<T> | EndsWith<T> | PartialByKeys<Record<string, string>, T>;

// 使用示例
type Test1 = TextFragmentSimilarity<'abc'>;
type Test2 = TextFragmentSimilarity<'xyz'>;
type Test3 = TextFragmentSimilarity<'efg'>;

// 正确
type Result1 = TextFragmentSimilarity<'abcdef'>;
type Result2 = TextFragmentSimilarity<'xyzxyz'>;
type Result3 = TextFragmentSimilarity<'abcefg'>;

// 错误
type Result4 = TextFragmentSimilarity<'defabc'>;
type Result5 = TextFragmentSimilarity<'zyx'>;

通过上面的例子,我们可以看到,TextFragmentSimilarity类型可以根据指定的子字符串来检查字符串的相似性,从而满足各种查询需求。

总结

在本文中,我们探索了StartWith、EndsWith和PartialByKeys这三个利器,并借助它们实现了文本片段相似性查询。这些利器可以帮助我们在类型定义和TS探索中更进一步,让我们写出更加优雅的TS代码。