当前位置:网站首页>20个实用的 TypeScript 单行代码汇总
20个实用的 TypeScript 单行代码汇总
2022-07-01 13:15:00 【仙凌阁】
在今天的文章中,我将与你分享20有用的 TypeScript 单行代码,这些单行代码可以快速的帮助我们提升开发效率,希望对你有用。
那我们现在开始吧。
01、等待特定的时间量(以毫秒为单位)
const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
await wait(1000); // waiting 1 second
02、检查日期是否为工作日
const isWeekday = (d: Date): boolean => d.getDay() % 6 !== ;
isWeekday(new Date(2022, 2, 21)); // -> true
isWeekday(new Date(2021, 2, 20)); // -> false
03、反转字符串
const reverse = (s: string): string => s.split('').reverse().join('');
reverse('elon musk'); // -> 'ksum nole'
04、检查一个数字是否为偶数。
const isEven = (n: number): boolean => n % 2 === ;
isEven(2); // -> true
isEven(3); // -> false
05、大写字符串
const capitalize = (s: string): string => s.charAt().toUpperCase() + s.slice(1);
capitalize('lorem ipsum'); // -> Lorem ipsum
06、检查数组是否为空
const isArrayEmpty = (arr: unknown[]): boolean => Array.isArray(arr) && !arr.length;
isArrayEmpty([]); // -> true
isArrayEmpty([1, 2, 3]); // -> false
07、检查对象/数组是否为空
const isObjectEmpty = (obj: unknown): boolean => obj && Object.keys(obj).length === ;
isObjectEmpty({
}); // -> true
isObjectEmpty({
foo: 'bar' }); // -> false
08、随机生成整数
基于两个参数生成一个随机整数。
const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;
randomInteger(1, 10); // -> 7
09、生成随机布尔值
const randomBoolean = (): boolean => Math.random() >= 0.5;
randomBoolean(); // -> true
10、切换布尔值
切换布尔值,变假为真,变真为假。
const toggleBoolean = (val: boolean): boolean => (val = !val);
toggleBoolean(true); // -> false
11、转换
将字符串转换为带“-”的连字字符串。
const slugify = (str: string): string => str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
slugify('Hello World'); // -> hello-world
12、生成随数组组合
随机生成一组任何类型的数组。
const shuffleArray = <T>(arr: T[]): T[] => arr.sort(() => Math.random() - 0.5);
shuffleArray(<number[]>[1, 2, 3, 4, 5]); // -> [ 4, 5, 2, 1, 3 ]
13、将连字字符串转换为骆峰字符串
const snakeToCamel = (s: string): string => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substring(1));
snakeToCamel('foo_bar'); // -> fooBar
14、随机整数
根据当前时间生成一个随机整数。
const randomInteger = (): number => new Date().getTime();
randomInteger(); // -> 1646617367345
15、随机数字符串
根据当前时间生成随机数字符串。
const randomNumberString = (): string => new Date().getTime() + Math.random().toString(36).slice(2);
randomNumberString(); // -> 1646617484381wml196a8iso
16、将数字转换为字符/字母
const numberToLetter = (value: number): string => String.fromCharCode(94 + value);
numberToLetter(4); // -> b
17、生成随机的十六进制颜色
const randomHexColor = (): string => `#${
Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;
randomHexColor(); // -> #dc7c40
18、删除字符串的尾部斜杠
const removeTrailingSlash = (value: string): string => value && value.charAt(value.length - 1) === '/' ? value.slice(, -1) : value;
removeTrailingSlash('foo-bar/'); // -> foo-bar
19、获取数组的随机项
const randomItem = <T>(arr: T[]): T => arr[(Math.random() * arr.length) | ];
randomItem(<number[]>[1, 2, 3, 4, 5]); // -> 4
20、将大写字符串转换为小写
const decapitalize = (str: string): string => `${
str.charAt(0).toLowerCase()}${
str.slice(1)}`;
decapitalize('Hello world'); // -> hello world
源码附件已经打包好上传到百度云了,大家自行下载即可~
链接: https://pan.baidu.com/s/14G-bpVthImHD4eosZUNSFA?pwd=yu27
提取码: yu27
百度云链接不稳定,随时可能会失效,大家抓紧保存哈。
如果百度云链接失效了的话,请留言告诉我,我看到后会及时更新~
开源地址
码云地址:
http://github.crmeb.net/u/defu
Github 地址:
http://github.crmeb.net/u/defu
来源 | https://blog.bitsrc.io/another-10-quick-typescript-one-liners-9f41713c158a
边栏推荐
- Shangtang technology crash: a script written at the time of IPO
- 2.15 summary
- Yarn重启applications记录恢复
- Machine learning - performance metrics
- codeforces -- 4B. Before an Exam
- Fiori 应用通过 Adaptation Project 的增强方式分享
- SVG钻石样式代码
- Development trend and market demand analysis report of China's high purity copper industry Ⓕ 2022 ~ 2028
- PG基础篇--逻辑结构管理(触发器)
- Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?
猜你喜欢

Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
![[Niu Ke's questions -sql big factory interview real questions] no2 User growth scenario (a certain degree of information flow)](/img/a0/e9e7506c9c34986dc73562539c8410.png)
[Niu Ke's questions -sql big factory interview real questions] no2 User growth scenario (a certain degree of information flow)

9. Use of better scroll and ref

【机器学习】VAE变分自编码器学习笔记

MySQL 66 questions, 20000 words + 50 pictures in detail! Necessary for review

不同的测试技术区分

彩色五角星SVG动态网页背景js特效

一款Flutter版的记事本

Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"

图灵奖得主Judea Pearl:最近值得一读的19篇因果推断论文
随机推荐
French Data Protection Agency: using Google Analytics or violating gdpr
PG basics -- Logical Structure Management (trigger)
C language learning
Update a piece of data from the database. Will CDC get two pieces of data with OP fields D and C at the same time? I remember before, only OP was U
Investment analysis and prospect prediction report of global and Chinese dimethyl sulfoxide industry Ⓦ 2022 ~ 2028
Apache-Atlas-2.2.0 独立编译部署
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
学历、长相、家境普通的人,未来的发展方向是什么?00后的职业规划都已经整得明明白白......
MySQL Replication中的并行复制示例详解
波浪动画彩色五角星loader加载js特效
Flinkcdc should extract Oracle in real time. What should be configured for oracle?
PG基础篇--逻辑结构管理(触发器)
1553B environment construction
Different test techniques
流量管理技术
Look at the sky at dawn and the clouds at dusk, and enjoy the beautiful pictures
Professor Li Zexiang, Hong Kong University of science and technology: I'm wrong. Why is engineering consciousness more important than the best university?
数字化转型再下一城,数字孪生厂商优锘科技宣布完成超3亿元融资
Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
Camp division of common PLC programming software