vuvu
vuvu

Reputation: 5338

What is a type object in typescript?

What is the type object and when is it used? It seems like a blackbox? Which solution A or B should be used, if a paramter can have unknown kinds of object keys?

A

const edit: (value: object) => void = value=> {// do something }

edit({name: "Bob", age: 11})

B

type JSONObject = { [k: string]: string | number}

const edit: (value: JSONObject ) => void = value=> {// do something }

Upvotes: 1

Views: 144

Answers (1)

Joshua McCarthy
Joshua McCarthy

Reputation: 1852

type is something you declare as a reference. In your B example if you run the following code:

const myObject:JSONObject = objFromFunction();
Object.values(myObject).map(objValue => { /* 'objValue' is of type 'string' or 'number' */ });

This is preferred over example A, where objValue would be of type any, which is a "black box" in the TypeScript environment.

When you are declaring a type, you're assigning a scope of potential values that can be assigned. Based on how edit() is used, you can setup various type strategies.


If you know the object will explicitly be {name:string, age:number} then you can declare your type as such:

type Person = { name:string; age:number };

If you only know that object properties may only contain a string or a number, then you would declare a type like your example, but you can use a Record:

type JSONObject = Record<string, string | number>;

Lastly, if you don't know the type contained within an object, I would recommend a slight change and use unknown

type JSONObject = Record<string, unknown>;

Using object will mark any property value as any which gives you no type protection. unknown gives you a little better type protection which I won't get into here. You should be able to find articles and Q&A about why to prefer unknown over any.

Upvotes: 1

Related Questions