mobily/ts-belt

Unsafely select keys from an object

Opened this issue · 2 comments

How can I select just a subset of keys from an object?

Consider this example in an express app. I want to validate the body, params, and query and want to use ts-belt to select just those three from the request. Is there a way to do this with ts-belt? Maybe a unsafeSelectKeys?

const validKeys = ['body', 'params', 'query']

const validReq = D.selectKeys(request, validKeys)

Thanks for the help!

@eckertalex sounds like a great idea, do you have any suggestion on how to tackle TS signature of D.unsafeSelectKeys?

I have been thinking about it the last couple of days and I am not sure if it is possible to have the correct typings if the keys exist and unknown if it.

In pseudo Typescript maybe something like this?

function selectKeysUnsafe<T, K extends Either<keyof T, unknown>>(dict: T, keys: ReadonlyArray<K>): Pick<T, K>

Basically the type of the keys would be either a key of T or unknown. But I think that way we would not have the correct return type?