Skip to content

Instantly share code, notes, and snippets.

@jose4125
Created January 27, 2020 17:03
Show Gist options
  • Select an option

  • Save jose4125/1e849be9d0bd0131569948150c7a586d to your computer and use it in GitHub Desktop.

Select an option

Save jose4125/1e849be9d0bd0131569948150c7a586d to your computer and use it in GitHub Desktop.
const names:Array<string> = [];
const promise: Promise<string> = new Promise((resolve) => {
setTimeout(() => {
resolve('this is done');
},2000)
})
promise.then(data => {
data.split('');
})
// CUSTOM TYPES
function merge<T, U>(objA: T, objB: U) {
return Object.assign(objA, objB);
}
const mergedObj = merge({name: 'jose'}, {age: 38})
console.log(mergedObj.name);
const mergedObj2 = merge({name: 'jose'}, 2)
// CUSTOM TYPES WITH CONSTRAINTS
function merge2<T extends object, U extends object>(objA: T, objB: U) {
return Object.assign(objA, objB);
}
const mergedObj3 = merge({name: 'jose'}, {age: 38})
// const mergedObj4 = merge2({name: 'jose'}, 2)
interface Lengthy {
length: number;
}
function countAndDescribe<T extends Lengthy>(element: T): [T, string] {
let descriptionText = 'got no value';
if (element.length === 1) {
descriptionText = `got 1 element`;
} else if (element.length > 1) {
descriptionText = `got ${element.length} elements`;
}
return [element, descriptionText];
}
// CONSTRAINTS - KEYOF
function extractAndConvert<T extends object, U extends keyof T>(obj: T, key: U) {
return obj[key];
}
// GENERIC CLASS
class DataStorage<T> {
private data: T[] = [];
addItem(item: T) {
this.data.push(item);
}
removeItem(item:T) {
this.data.splice(this.data.indexOf(item), 1);
}v
getItems() {
return [...this.data];
}
}
const textStorage = new DataStorage<string>();
textStorage.addItem('jose');
const numberStorage = new DataStorage<number>();
numberStorage.addItem(4);
// PARTIAL
interface CourseGoal {
title: string;
description: string;
completeUntil: Date;
}
function createCourseGoal(title: string, description: string, date: Date): CourseGoal {
let courseGoal: Partial<CourseGoal> = {};
courseGoal.title = title;
courseGoal.description = description;
courseGoal.completeUntil = date;
return courseGoal as CourseGoal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment