Skip to content

Instantly share code, notes, and snippets.

@anilpai
Created March 27, 2021 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anilpai/3684bd4caa1fe8f4da847f57e9a80602 to your computer and use it in GitHub Desktop.
Save anilpai/3684bd4caa1fe8f4da847f57e9a80602 to your computer and use it in GitHub Desktop.
TypeScript
type Salutation = {greeting: string, name: string}
/**
* @param {Salutation}
* @return {string}
*/
function greet1({greeting, name}: Salutation):string{
return `${greeting}, ${name}`
}
const message:string = greet1({greeting: "Hello", name:"John"})
const input = document.getElementById("input") as HTMLInputElement
input.autofocus = true
input.addEventListener("input", event => {
const i = event.currentTarget as HTMLInputElement
console.log(i.value)
})
function fill<T>(array: any[], value: T): T[]{
return array.map(()=> value)
}
const result = fill([1,2,3], "a")
const values = fill(["a", "b", "c"], 4)
function identity<T>(arg: Array<T>) :T[] {
console.log(arg.length)
return arg;
}
let output = identity<string>(["myString"]);
// Working with Generic Type Variables
function identity2<T>(arg: T) :T {
return arg;
}
let myIdentity : <T>(arg: T) => T = identity2;
let myIdentity2 : <Input>(arg: Input) => Input = identity2;
let myIdentity3 : { <Type>(arg: Type): Type } = identity2;
// Generic Types
interface GenericIdentityFn<T> {
(arg: T): T
}
let myIdentity4 : GenericIdentityFn<number> = identity2
//Generic Classes
class GenericNumber<NumType> {
zeroValue : NumType;
add : (x: NumType, y:NumType) => NumType;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x,y) {
return x+y;
};
let stringGeneric = new GenericNumber<string>();
stringGeneric.zeroValue = "";
stringGeneric.add = function(x, y) {
return x+y;
};
console.log(stringGeneric.add(stringGeneric.zeroValue, "test"))
// Generic Constraints
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length)
return arg;
}
// loggingIdentity(3) // generic function is now constrained, it will no longer work over any and all types
loggingIdentity({length: 10, value: 3}) // pass in values whose type has all the required properties
// Using Type Parameters in Generic Constraints
function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
let x = {a:1, b:2, c:3, d:4}
getProperty(x, "a")
// getProperty(x, "m") //Error
// Using Class Types in Generics
function create<Type>(c: { new () : Type}): Type {
return new c();
}
class BeeKeeper {
hasMask : boolean;
}
class ZooKeeper {
nametag : string;
}
class Animal {
numLegs : number;
}
class Bee extends Animal {
keeper: BeeKeeper
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;
function greet(person: string, data: Date){
console.log(`Hello ${person}, today is ${data.toDateString()}!`)
}
greet("Anil", new Date())
let obj:any = {x : 0}
obj.foo()
obj()
const n : number = obj
// Anonymous Functions
const names = ["Alice", "Bob", "Eve"]
names.forEach(function(s) {
console.log(s.toUpperCase())
})
names.forEach((s) => {
console.log(s.toUpperCase())
})
// Object Types
function printCoord(pt: {x :number, y?: number}){
console.log("The coordinate's x value is"+ pt.x)
console.log("The coordinate's y value is"+ pt.y)
}
printCoord({x:3, y:7})
printCoord({x:5})
function printName(obj: { first: string; last?: string }) {
// Error - might crash if 'obj.last' wasn't provided!
console.log(obj.last.toUpperCase());
if (obj.last !== undefined) {
// OK
console.log(obj.last.toUpperCase());
}
// A safe alternative using modern JavaScript syntax:
console.log(obj.last?.toUpperCase());
}
// Union Types
function printId(id: string | number){
console.log("Your ID is:"+ id)
}
printId(101)
printId("202")
// printId({myID: 22342})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment