Typescript
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
Links, Courses and Tutorials about Typescript.
Get help with Typescript from the community or creators.
Many modern frameworks like Next.js already have first-class Typescript support. In case you would like to set it up manually though, here are the steps:
Terminal
npm install -D typescript
Next, you need a
tsconfig.json
to configure important parameters, like how to transpile your code and where to store the .js
output.Terminal
npx tsc --init
This will output a
tsconfig.json
file at the root of your project:tsconfig.json
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "./dist" }}
We can highly recommend Matt Pocock's Typescript Cheat Sheet to understand what all the fields in your
tsconfig.json
mean.You can now add
.ts
files to your project, with type support:index.ts
const world = 'world'export function hello(who: string = world): string { return `Hello ${who}! `}
And can compile them to Javascript in your
dist
folder by running:Terminal
npx tsc
The compiled code of above example will look like this and can be run in every browser:
dist/index.js
'use strict'Object.defineProperty(exports, '__esModule', { value: true })exports.hello = void 0const world = 'world'function hello(who = world) { return `Hello ${who}! `}exports.hello = hello
Helper Types
Helper Types are reusable types that you can use in your whole project for various purposes!
Prettify
helpers.ts
export type Prettify<T> = { [K in keyof T]: T[K]} & {}/** * { a: string; } & { b: number; } & { c: boolean; } */type Intersected = { a: string} & { b: number} & { c: boolean}/** * { * a: string; * b: number; * c: boolean; * } */type PrettyIntersected = Prettify<Intersected>
Credits: Total Typescript
EventFor
helpers.ts
type GetEventHandlers<T extends keyof JSX.IntrinsicElements> = Extract< keyof JSX.IntrinsicElements[T], `on${string}`>export type EventFor< TElement extends keyof JSX.IntrinsicElements, THandler extends GetEventHandlers<TElement>,> = JSX.IntrinsicElements[TElement][THandler] extends | ((e: infer TEvent) => any) | undefined ? TEvent : neverconst onChange = (e: EventFor<'input', 'onChange'>) => { console.log(e)};<input onChange={onChange} />
Credits: Total Typescript