quasi
quasi

Reputation: 441

Angular: empty array as property of typed object

so I have a model:

export interface Clan {
  name: string;
  members: [string];
  invitees: [string];
}

When the user creates a new clan it does not has yet invitees, only one member.

newClan = {
   name: form.value.name;
   members: [user.id];
   invitees: [];
}

And this gives the an error

Property '0' is missing in type '[]' but required in type '[string]'.

Of course I could use values as null or undefined, also or just define invitees in the model as not required:

export interface Clan {
  name: string;
  members: [string];
  invitees?: [string];
}

But is there a way to have an invitees empty array on the creation of a new clan?

Upvotes: 1

Views: 2419

Answers (1)

pzaenger
pzaenger

Reputation: 11973

I guess, it might be reasonable to use string[] instead of [string], because [string] is an array with exact one string in it.

export interface Clan {
  name: string;
  members: string[];
  invitees: string[];
}

const newClan: Clan = {
   name: form.value.name;
   members: [user.id];
   invitees: [];
}

Edit: @R. Richards comment offers a good explanation. Read here more about tupels in TypeScript:

Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.

Upvotes: 6

Related Questions