One time setup
npm i -g typescript ts-node
tsc --help
To Run: tsc index.ts node index.js OR ts-node index.ts
React with Typescript
npx create-react-app my-app --template typescript OR npx create-react-app . --template typescript
npm init -y
It creates package.json
file
index.ts
filetsc index.ts node index.jsOR
ts-node index.ts
interface Todo { id: number; title: string; } axios.get(url).then(response => { const todo = response.data as Todo; const id = todo.id; const title = todo.title; });
const profile = { fullName: "Alex Doe", age: 20, coords: { lat: 0, lng: 15 }, setAge(age: number): void { this.age = age; } } const { age }: {age: number} = profile; const { coords: { lat, lng }, }: { coords: { lat: number; lng: number } } = profile;
'map'
const carMakers: string[] = ['ford', 'toyota', 'chevy']; carMakers.map((car: string): string => { return car.toLowerCase(); });
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { }
const dest = ({ a, b }: { a: number; b: string; } = { a: 1, b: "asdf"}): void => { };
const logWeather2 = ({ date, weather, }: { date: Date; weather: string; }): void => { console.log(date, weather); };
const importantDates: (Date | string)[] = [new Date()];
type Drink = [string, boolean, number]; const drink1: Drink = ["brown", true, 40]; const tea: Drink = ["clear", false, 0];
/* eslint-disable */ // @ts-nocheck // TODO: REMOVE NOCHECK
interface Vehicle { name: string; year: Date; broken: boolean; summary(): string; // function } const oldCivic = { name: "civic", year: new Date(), broken: true, summary(): string { return `Name ${this.name}` } };
function printAnyThing<T>(arr: T[]): void { for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } } printAnyThing<string>(["a", "b", "c"]); // specify type to catch errors
class Car { print() { console.log("I am a car"); } } class House { print() { console.log("I am a house"); } } interface Printable { print(): void; } function printHousesOrCars<T extends Printable>(arr: T[]): void { for (let i = 0; i < arr.length; i++) { arr[i].print(); } } printHousesOrCars<House>([new House(), new House()]);
class Vehicle { // Parent class drive(): void { console.log('driving...') } } class Car extends Vehicle { // Child class drive(): void { console.log("vroom"); } }
Default - this method can only be called any where
This method can only be called by other methods in this class, or by other methods in child class
This method can only be called by other methods in this class
class Vehicle { constructor(public color: string) { // creates and initializes public field 'color' . Can be also protected or private } } const vehicle = new Vehicle('orange');
class Vehicle { constructor(public color: string) { } } class Car extends Vehicle { constructor(public wheels: number, color: string) { // color is a property of the parent class super(color); } }
When function never returns value - there is no chance to reach the end of the function because function throws some Error
Functions that returns void technically may return
null
or undefined
interface Props { color?: string } const MyComponent = ({ color }: Props): JSX.Element => { const [counter, setCounter] = useState<number>(0); }
const onSubmit = (e: React.FormEvent<HTMLFormElement>): void => {}OR
type FormElem = React.FormEvent<HTMLFormElement> const onSubmit = (e: FormElem): void => {}