GithubHelp home page GithubHelp logo

aakashvani / learning_typescript Goto Github PK

View Code? Open in Web Editor NEW

This project forked from akshay-singh-rajput/learning_typescript

0.0 0.0 0.0 23 KB

created a mini project while learning typescript

Home Page: https://typescript-financelogger.netlify.app/

JavaScript 43.02% TypeScript 49.64% CSS 3.29% HTML 4.06%

learning_typescript's Introduction

Typescript CheatSheet

Learn Typescript

Setup

Install Ts Globally on your machine

npm i -g typescript

check version

tsc -v

create the tsconfig.json file

tsc --init

set the root(to complie TS files from) and output(for the complied Js files) directories in tsconfig.jsx

"rootDir" : "./src",
"outDir" : "./public",

Compiling

Compile a specified Ts file into a Js file of the same name, into the same directory(i.e. index.ts to index.js).

tsc index.ts

Tell tsc to complie specified file whenever a change is saved by adding the watch flag(-w)

tsc index.js -w

Compile specified file into specified output file

tsc index.ts --outfile out/script.js

if no file is specified , tsc will complie all TS files in the "rootDir" and output in the "outDir". Add -w to watch for changes.

tsc -w

Strict Mode

In tsconfig.json, it is recommended to set strict to true. One helpful feature of strict mode is No Implicit Any:

//Error : Parameter 'a' implicity has an 'any' type
function logName(a){
    console.log(a.name)
}

Primitive Types

There are 7 primitive types in JS:

string, number, bigInt, boolean,undefined,null,symbol

Explicit type annotation

let firstname : string = 'Danny'

if we assign a value (as above), we don't need to state the type - TS will infer it("implicit type annotation")

let firstname = 'Danny'

Union Types

A variable that can be assigned more that one type

let age : number | string
age = 26;
age = '25';

Dynamic Types

The any type basically reverts TS back to JS.

let age : any = 100;
age = true;

Literal Types

We can refer to specific string & numbers in type positions

let direction : 'UP' | 'DOWN';
direction = 'up';

Objects

Objects in Ts must have all the correct properties & value types

let person : {
    name : string;
    isProgrammer : boolean;
};


person = {
    name : 'Danny',
    isProgrammer : true
};


person.age = 26; // Error - no age prop on person object

person.isProgrammer = 'yes'; // Error - should be boolean

Arrays

We can define what kind of data an array can contain

let ids : number[] = [];
ids.push(1);
ids.push("2"); // Error

Use a union type for arrays with multiple types

let options : (string | number)[];
opptions = [10,'up'];

if a value is assigned, TS will infer types in the array.

let person = ['Delia', 48];
person[0] = true; //Error - only string or numbers allowed

Tuples

A tuple is a special type of array with fixed size & known data types at each index. They're stricter than regular arrays.

let options : [string, number];
options = ['UP', 10];

Functions

We can define the types of the arguments, and the return type. Below : string could be omitted because TS would infer the return type.

function circle(diam : number): string {
    return 'Circumf = ' + Math.PI * diam;
}

The same function as an ES6 arrow

const circle = (diam : number) : string => {
    'Circumf = ' + Math.PI * diam;
}

If we want to declare a function but not define it use a function signature

let sayHi : (name : string) => void;

sayHi = (name : string) => 
console.log('Hi" + name);

sayHi('Danny'); //Hi Danny

Type Aliases

Allow you to create a new name for an existing type. Type can help to reduce code duplication. They're similar to interfaces, but can also describe primitive types.

type StringOrNum = string | number;
let id : StringOrNum = 24;

Interfaces

Interfaces are used to describe objects. Interfaces can always be reopened & extended, unlike Type Aliases. Notice that name is readonly

interface Person {
    name : string;
    isProgrammer : boolean:
}

let p1 : Person = {
    name 'Delia',
    isProgrammer : false,
};

p1.name = 'Del'; // Error - read only

Two ways to describe a function in an inrerface

interface Speech {
    sayHi(name : string) : string;
    sayBye : (name : string) => string;
}

let speech : Speech = {
    sayHi : function (name : string){
        return 'Hi' + name;
    },
    sayBye : (name: string) => 'Bye ' + name,
}

Extending an interface

interface Animal {
    name : string;
}

interface Dog extends Animal {
    breed : string;
}

The DOM & Type Casting

Ts doesn't have access to the Dom, so use the non-null operator, !, to tell Ts the expression isn't null or undefined

const link = document.querySelector('a)!;

If ab element is selected by id or class, we need to tell TS what type of elementit is via Type Casting

const form = document.getElementById('singup-form') as HTMLFormElement;

Generics

Generics allow for type safety in components where the arguments & return types are unkown ahead of time.

interface HasLength {
    length : number;
}

// logLength accepts all types with a length property
const logLength = <T extends HasLength>(a : T) => {
    console.lgo(a.length)
};

// Ts "captures" the type implicity
loglength('Hello'); //5

// Can also explicitly pass the type to T
logLength<number[]>([1,2,3]); //3

Declare a type, T, which can change in your interface.

interface Dog<T> {
    breed : string;
    treats : T;
}

// We have to pass in a type argument
let labrador : Dog<string[]> = {
    breeed : 'scottish terrier',
    treats : ['turkey', 'haggis'],
};

Enums

A set of related values, as a set of descriptive constanst

enum ResourceType {
    BOOK,
    FILE,
    FILM
}

ResourceType.BOOK; // 0
ResourceType.FILE; // 1

Narrowing

Occurs when a variable moves from a less precise type to a more precise type

let age = gerUserAge();
age // string | number

if(typeof age === 'string') {
    age; // string
}

More Example

Official Doc

Cheatsheet Images

image image image image

learning_typescript's People

Contributors

akshay-singh-rajput avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.