Xtensions
Bring extensions to TypeScript.
Installation
npm
npm install xtensions
yarn
yarn add xtensions
pnpm
pnpm add xtensions
Usage
Let's use a minimal example to show how to use Xtensions.
import { extension, extensions } from 'xtensions';
const stringExtensions = extension('string', (s) => ({
emphasize: (level: number) => s + '!'.repeat(level),
}));
const numberExtensions = extension('number', (n) => ({
add: (x: number) => n + x,
double: () => n * 2,
}));
const intervalExtensions = extension({
start: 'Date | number',
end: 'Date | number',
}, (i) => ({
duration: () => {
const start = typeof i.start === 'number' ? i.start : i.start.getTime();
const end = typeof i.end === 'number' ? i.end : i.end.getTime();
return end - start;
},
}));
const ex = extensions.use(stringExtensions, numberExtensions, intervalExtensions);
const interval = { start: new Date('2023-01-01'), end: new Date('2023-01-02') };
const duration = ex(interval).duration();
const emphasized = ex('Hello').emphasize(3).toString();
const doubled42 = ex(42).double().valueOf();
const doubledDuration = ex(interval).duration().double();
Xtensions uses ArkType, a truly powerful and natural validator for TypeScript, to infer the type according to definition (like 'string'
-> string
, { start: 'Date | number', end: 'Date | number' }
-> { start: Date | number; end: Date | number }
), and validate the types of input (i.e. choose the correct extension to use). You can visit its website to learn more how to define more complex types for your extensions.
You can view the recommended way to use Xtensions in a real project in the examples/
directory. It is recommended to start from examples/basic
.