Skip to content

Instantly share code, notes, and snippets.

@nik-1207
Last active September 18, 2021 06:26
Show Gist options
  • Save nik-1207/3d026291f17a34c07dca865e0f4a562b to your computer and use it in GitHub Desktop.
Save nik-1207/3d026291f17a34c07dca865e0f4a562b to your computer and use it in GitHub Desktop.
Cheatsheet for ts
/*Compilation */
tsc filename.ts //to compile a ts file
tsc filename.ts -w //to compile a ts file with watch flag
/*Project configuration*/
"outDir":"path" //add in tsconfig in compiler options
"rootDir":"path"//add tsconfig in ccompiler options
"include":["foldername"] before last closing parenthesis add this line
tsc -w // in terminal
/*Decleration of variables & function parameters*/
var varname:type=value; //declare type and value
var varname:type; //declare type
var varname=value; //declare value and type will be assigned automatically
var varame; //type will be of first assigned value
/*Decleration of arrays*/
var varname:string[]=[] //default type array with nul values
/*Decleration of object*/
variables declared under object must have same name under object assignment
var varname:object
varname={
param1:string,
param2:strng
}
/*union type array*/
let mixed:(string|number|boolean)[]=[] //array with multile type and null values
/*any type*/
let varname:any
/*Function Decleration */
void is also a return type
let function name:Funcction
let function=(param1:type,param2:type param3?:type1|type2|type3=defaultvalue)=>{}
let function =(param1:type,param2:type):return type=>
{
return value
}
let function :(param1:type,param2:type)=>returntype
function =(param1:type,parma2:type)=>
{
implementation
}
/*Type aliases*/
type typename=type1|type2|type3
/*without generics*/
// const addUID = (obj: object) => {
// let uid = Math.floor(Math.random() * 100);
// return {...obj, uid};
// }
addUID({parma1:asd}) //allowed but dont want to include it
addUID({parma1:asd,param2:asd}) //allowed what we want
/* Generics */
// const addUID = <T extends object>(obj: T) => {
// let uid = Math.floor(Math.random() * 100);
// return {...obj, uid};
// }
addUID({parma1:asd}) //allowed but dont want to include it
addUID({parma1:asd,param2:asd}) //allowed what we want
// const addUID = <T extends {parma1:type,param2:type}>(obj: T) => {
// let uid = Math.floor(Math.random() * 100);
// return {...obj, uid};
// }
addUID({parma1:asd}) //not allowed what we want
addUID({parma1:asd,param2:asd}) //allowed what we want
/* with Interface */
interface Resource<T> {
uid: number;
resourceName: string;
data: T;
}
const docThree: Resource<object> = {
uid: 1,
resourceName: 'person',
data: { name: 'shaun' }
};
const docFour: Resource<string[]> = {
uid: 1,
resourceName: 'shoppingList',
data: ['bread', 'milk']
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment