Hi guys, long time no new articles!
In this article, I am going to show the way to enforce TypeScript types in the runtime environment.
Photo by Andre Benz on Unsplash
| yarn add [email protected] | |
| import { validate } from './common.types.validator'; | |
| // Just give example situation to get unknown data | |
| const rawProductValue: unknown = { | |
| id: 1, | |
| name: 'Table 1', | |
| type: 'Invalid type', | |
| quantity: 5, | |
| }; | |
| const parsedProduct = validate('Product')(rawProductValue); | |
| console.log('Parsed product', parsedProduct); |
| npx typescript-json-validator --id ./src/common.types.ts --collection ./src/common.types.ts |
| // common.types.ts | |
| export interface Product { | |
| id: number; | |
| name: string; | |
| quantity: number; | |
| type: 'FURNITURE' | 'BOOK'; | |
| } | |
| export type FastType = string | number; |
Hi guys, long time no new articles!
In this article, I am going to show the way to enforce TypeScript types in the runtime environment.
Photo by Andre Benz on Unsplash
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Tab 1</title> | |
| </head> | |
| <body> | |
| <button>Send broadcast message</button> |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Event bubbling & capturing</title> | |
| <style> | |
| * { | |
| box-sizing: border-box; |
| // it.each`table`(name, fn, timeout) | |
| it.each` | |
| var1 | var2 | expectedResult | |
| ${1} | ${2} | ${3} | |
| ${2} | ${3} | ${5} | |
| `('should work', ({ var1, var2, expectedResult }) => { | |
| expect(yourFn(var1, var2)).toEqual(expectedResult); | |
| }); |
| const createTransform = ( | |
| pattern: string | RegExp, | |
| separator: string, | |
| wordTransformer: (word: string) => string, | |
| ) => (text: string) => text.split(pattern).map(wordTransformer).join(separator); | |
| const exhaustedPattern = /[\s_-]|(?=[A-Z0-9])/; | |
| export const toKebabCase = createTransform(exhaustedPattern, '-', (word) => | |
| word.toLowerCase(), |