Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New utility type: Widen object's primitives #166

Open
pelhage opened this issue Jun 21, 2021 · 0 comments
Open

New utility type: Widen object's primitives #166

pelhage opened this issue Jun 21, 2021 · 0 comments

Comments

@pelhage
Copy link

pelhage commented Jun 21, 2021

Is your feature request related to a real problem or use-case?

I have a specific object but would like to hide the actual values to be a bit wider:

const a = {
  foo: 'hello',
  bar: 45
}

const current = a.bar // type 45
// use a wider type
const desired= a.bar // type number

^^ i understand that using const vs let can have this happen, but I'm mostly interested in having tighter control and ensuring the wider type is always what is seen by the end user.

The intent here is to obfuscate the implementation details of certain objects because they are deemed irrelevant to the dev and subject to change at any time

Describe a solution including usage in code example

I have a working example based on https://stackoverflow.com/questions/59355418/widen-a-type-with-a-type-generic-in-typescript but we'd need to modify it to better handle nested objects and potentially arrays?

However my typescript-fu is not quite there yet and would need some help:

/**
 * We'd like to widen our types to not leak their implementation.
 * For example, when looking at types or auto-complete 
 * a user should see:
 * - Sizes.Small as `string` instead of:
 * - Sizes.Small as `16`
 */
// Taken from https://stackoverflow.com/questions/59355418/widen-a-type-with-a-type-generic-in-typescript
// it transforms our specific types into primitive origins
type ToPrimitive<T> =
  T extends string
  ? string
  : T extends number
  ? number
  : T extends boolean
  ? boolean
  : T;
// mapped types which will preserve keys with more wide value types
type Widen<O> = {
  [K in keyof O]: ToPrimitive<O[K]>
}

Who does this impact? Who is this for?

This is for anyone who would like to map an object type while using wider primitive types (me)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant