[Typescript] Generics in a Class Names Creator
typescript in Class Creator names generics
2023-09-14 08:59:11 时间
Consider this createClassNamesFactory
function that's similar to one I built for getting Tailwind class names that could then be passed into a React component
const createClassNamesFactory =
(classes: unknown) =>
(type: unknown, ...otherClasses: unknown[]) => {
const classList = [classes[type], ...otherClasses];
return classList.join(" ");
};
For example, after creating a getBg
factory, calling getBg('primary')
will return 'bg-blue-500'
.
This pattern is common in instances where you have a lot of class names you want to be able to stack in various configurations.
Solution:
import { expect, it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';
const createClassNamesFactory =
<T extends { primary: string; secondary: string }>(classes: T) =>
(type: keyof T, ...otherClasses: string[]) => {
const classList = [classes[type], ...otherClasses];
return classList.join(' ');
};
const getBg = createClassNamesFactory({
primary: 'bg-blue-500',
secondary: 'bg-gray-500',
});
it('Should let you create classes from a className factory', () => {
expect(getBg('primary')).toEqual('bg-blue-500');
expect(getBg('secondary')).toEqual('bg-gray-500');
});
it('Should let you pass additional classes which get appended', () => {
expect(getBg('primary', 'text-white', 'rounded', 'p-4')).toEqual(
'bg-blue-500 text-white rounded p-4'
);
});
it('Should return a type of string', () => {
const result = getBg('primary');
type test = Expect<Equal<typeof result, string>>;
});
it('Should not let you pass invalid variants', () => {
// @ts-expect-error
getBg('123123');
});
it('Should not let you pass an invalid object to createClassNamesFactory', () => {
// @ts-expect-error
createClassNamesFactory([]);
// @ts-expect-error
createClassNamesFactory(123);
createClassNamesFactory({
// @ts-expect-error
a: 1,
});
});
相关文章
- 如何处理TypeScript中的可选项和Undefined
- 基于 Vue3、TypeScript、Vite2、Pinia 开源的后台管理框架
- Typescript教程_安装typescript
- typeScript 全局库 文件声明
- TypeScript 中 type 和 interface 有什么区别?
- TypeScript方法装饰器应用
- 12个 Typescript 开发实用技巧清单
- 软件开发入门教程网之TypeScript 基础语法
- 软件开发入门教程网之TypeScript 类
- Laravel + Vue 3(Vite、TypeScript)SPA 设置
- Webpack搭建简单的TypeScript脚手架
- TypeScript遭库开发者嫌弃:类型简直是万恶之源
- 在TypeScript中使用装饰器
- 进行字符串比较使用Oracle IN运算符比较字符串(oracle使用in)
- 运算MySQL无法使用IN操作(mysql不能用in)
- 和existsMySQL首选:少用IN和EXISTS方法(mysql少用in)
- MySQL 中的 IN 语句分析(mysql语句in)
- Oracle中使用IN函数查找元素(oracle 函数 in)
- MSSQL中的ID IN查询使用技巧(mssql id in)
- MySQL的IN操作符对于查询中给定的值列表长度是有限制的(mysql中in长度限制)
- 解析MySQL中IN操作符的实现原理(mysql中in的原理)
- Oracle的IN走索引技术(in走索引 oracle)
- MySQL不支持IN运算符如何解决(mysql 不支持in)
- 查询Oracle IN查询两个字段的精彩之处(oracle两个字段in)
- Oracle IN一种SQL语句查询的高效方式(oracle in的定义)