Untitled

mail@pastecode.io avatar
unknown
typescript
a month ago
1.5 kB
1
Indexable
Never
const isArray = <T, >(value: unknown): value is Array<T> => {
    if (Array.isArray(value)) {
        return true
    }

    return false
}

const isObject = <T, >(value: unknown): value is { [K in keyof T]: T[K] } => {
    if (value === null) {
        return false
    }
    return typeof value === 'function' || typeof value === 'object'
}

const isString = (value: unknown): value is string => {
  return typeof value === 'string' || value instanceof String
}

const isNumber = (value: unknown): value is number => {
  return typeof value === 'number'
}

const isBigInt = (value: unknown): value is bigint => {
  return typeof value === 'bigint'
}

const isBoolean = (value: unknown): value is Boolean => {
  return typeof value === 'boolean' || value instanceof Boolean
}

const isSymbol = (value: unknown): value is Symbol => {
  return value instanceof Symbol
}

const serializeUnknownToString = (value: unknown): string => {
  if (value === undefined || value === null) {
    // @todo: wtf is happening here?
    throw new Error('Cannot serialize undefined or null to a string.')
  }

  if (isNumber(value) || isBigInt(value) || isBoolean(value) || isSymbol(value)) {
    return value.toString()
  }

  if (isObject(value) || isArray(value)) {
    return JSON.stringify(value)
  }

  return value // @note: Should be never
}

type Json = string | number | boolean | null | { [key: string]: Json } | Json[];

console.debug({ value: serializeUnknownToString(undefined) })
Leave a Comment