1

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?

2
  • 1
    Just an FYI. [string] is how you declare a tuple that will contain a string in typescript, at least the start of a tuple. Usually, you will have more than one type in a tuple. string[] is how you declare an array of type string. Commented Jul 20, 2019 at 12:18
  • Now I understand, Thx @R.Richards. Went back to read about tuples. Your answer is actually the correct one! Commented Jul 20, 2019 at 13:15

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I prefer R. Richards explication. Because it explains why I still can have multiple values in what I though was an array. (see comments of question) Thank you!
That's true and a good point. Therefore I added a link to the accordant TypeScript part about tupels.
Strange they define it with "fixed number of elements" as I still can push new elements into it as long as I'm using the same type. Or I am misinterpreting the definition?
Mmh. If I do something like const bar: [number] = [1, 1];, which is one element too many, I get the following error: Type '[number, number]' is not assignable to type '[number]'. Types of property 'length' are incompatible.
However, string[] is not a tuple but an array. Therefore you can push element by element.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.