Bill
Bill

Reputation: 5150

Typescript: Conditionally add items to an object

if I make an object

const data = {}

then try and add an object to it

const data = {};
data.shared = {};

I get the error Property 'shared' does not exist on type '{}'.ts(2339)

I add it in manually

const data = {
    shared: {},
};

and then I'm back to the same issue when I want to conditionally add a value

if (true) data.shared.username = 'test'

Property 'username' does not exist on type '{}'.

Upvotes: 1

Views: 1883

Answers (2)

Tom Mettam
Tom Mettam

Reputation: 2963

While apokyrfos's answer is correct, best practice with Typescript is to avoid any when possible - using the any type defeats the benefit of using Typescript in the first place.

What you can do is declare your object with an index signature:

const data: {[key: string]: SomeType} = {};

This way, you can assign data.shared at any time without an issue, as long as the type you're assigning is permitted by "SomeType" (If you have different but similar objects which may be assigned here, consider using an interface).

Upvotes: 2

Plastic
Plastic

Reputation: 10328

I will create an Interface to define the data structure, like this:

interface IData {
    shared?:{
        username?: string;
        // here any other properties you want to conditionally add
    }
}

in this way the compiler always know what to expect

then you can declare data as:

const data: IData = {}

Upvotes: 4

Related Questions