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
type SomeObjectType;
type AnotherObjectType;
type AnyOtherObjectYouWantToAddType;
const isPresentObjectGeneric = <T>(arg: T): boolean => {
if (arg && Object.keys(arg).length > 0) {
return true;
}
return false;
}
const identity = <T>(arg: T): T => arg;
identity<string>('someString'); //would return 'someString'
identity<number>(12); //would return 12
identity<boolean>(false); //would return false
@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;
@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;
@meekg33k
meekg33k / some-object-type-another-object-type.ts
Last active March 31, 2020 11:27
Util function now supports AnotherObjectType https://medium.com/p/177b4a654ef6
type ObjectType = SomeObjectType | AnotherObjectType | undefined;
const isPresentSomeAnotherObject = (arg: ObjectType): boolean => {
if (arg && Object.keys(arg).length > 0) {
return true;
}
return false;
}
if (isPresentSomeObject(someObject)) {
//Back off compiler, I got this!
someObject!.id = 12;
}
@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
}
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
}