Skip to content

Instantly share code, notes, and snippets.

View meekg33k's full-sized avatar
🇮🇴
It's all 0's and 1's

Uduak 'Eren meekg33k

🇮🇴
It's all 0's and 1's
View GitHub Profile
@meekg33k
meekg33k / is-present-some-object.ts
Last active January 17, 2020 17:11
A utility function to check if an object is present
const isPresentSomeObject = (arg: SomeObjectType | undefined): boolean => {
if (arg && Object.keys(arg).length > 0) {
return true;
}
return false;
}
@meekg33k
meekg33k / some-object-updated.ts
Last active January 17, 2020 17:15
Updated logic to check if an object is really not empty https://medium.com/p/177b4a654ef6
if (someObject && Object.keys(someObject).length > 0) {
//Our updated test to check if an object is really not empty
}
@meekg33k
meekg33k / identity-function-for-types.ts
Last active January 17, 2020 17:16
Identity function for different types https://medium.com/p/177b4a654ef6
const identityStringFn = (arg: string): string => arg;
const identityNumberFn = (arg: number): number => arg;
const identityBooleanFn = (arg: boolean): boolean => arg;
interface Cat {
meow();
walk();
}
interface Dog {
bark();
walk();
}
@meekg33k
meekg33k / check-animal-type-using-type-assertion.ts
Last active January 17, 2020 17:17
Logic to check if an animal type using type assertion https://medium.com/p/177b4a654ef6
const isCat = (animal: Animal):boolean => {
return (animal as Cat).meow
}
const isDog = (animal: Animal): boolean => {
return (animal as Dog).bark
}
const isCat = (animal: Animal): animal is Cat => {
//Hey compiler, this animal is a Cat
return true;
}
type SomeObjectType = {
id: number;
text: string;
}
let someObject: SomeObjectType | undefined;
if (someObject && Object.keys(someObject).length > 0) {
//This evaluates as truthy because it's not undefined
someObject.id = 12; //TS compiler doesn't complain here because the object exists
}
if (isPresentSomeObject(someObject)) {
//Back off compiler, I got this!
someObject!.id = 12;
}
@meekg33k
meekg33k / is-present-any.ts
Last active March 31, 2020 09:29
Utility function with argument of type any https://medium.com/p/177b4a654ef6
//Keep adding more types to the union, good luck with that
type ObjectType = SomeObjectType | AnotherObjectType
| ... | AnyOtherObjectYouWantToAddType | undefined;
//OR
//Just make the argument of type any 😱
const isPresentAny = (arg: any): boolean => {
if (arg && Object.keys(arg).length > 0) {
return true;
type SomeObjectType;
type AnotherObjectType;
type AnyOtherObjectYouWantToAddType;
const isPresentObjectGeneric = <T>(arg: T): boolean => {
if (arg && Object.keys(arg).length > 0) {
return true;
}
return false;
}