Typescript Object Keys and Values

Typescript Object Keys and Values

Exercise in Typescript Typing

Part One

Setup

This is a quick challenge... assume we need a function objectKeys() that returns all of the property names of the argument passed in.

Challenge

Implement the function objectKeys() listed below so that if value is an object, the function returns an array of the object's property names (keys). If it is not an object, return false.

typescript
1function objectKeys(value: unknown): string[] | false {
2  /* ... implement ... */
3}

One Solution

Part Two

Setup

In the previous challenge, we were able to get all of the keys of an object and we could use that array to get all of the keys that match some criteria (e.g. starts with some prefix). We could then get the values associated with those filtered keys using the original object. The problem is that we need two entities (the keys and the original object).

typescript
1// Get the keys and associated values of `obj` where the keys start with an underscore...
2
3const obj = { /* define props */ }; //some object
4
5const keys = (objectKeys(obj) || []).filter(key => key.startsWith('_'));
6const values = keys.map(key => obj[key]);

Challenge

We can bring both the keys and values into a single entity by transforming the object into a KeyValue array.

typescript
1type KeyValue = {
2	key: string;
3	value: unknown
4}

Implement the function toKeyValueArray() listed below so that if obj is an object, the function returns an array of KeyValue. If it is not an object, then return false.

typescript
1function toKeyValueArray(obj: unknown): KeyValue[] | false {
2	/* ... implement ... */
3}

One Solution


Part Three

Challenge

To enhance toKeyValueArray() let's add an optional predicate parameter that (if it exists) will be used to filter the keys returned by the method. For example, toKeyValueArray(obj, (key: string) => key.startsWith('_')) will return an array of KeyValue where all of the keys will start with an underscore.

One Solution

popularity
Electric
posted
Aug. 21, 2024