I know how to declare the type in a variable.
let members: string[] = [] // this works perfectly
I want to have an array of strings in an object. How can I format it correctly?
const team = {
name: String,
members<string[]>: [], // this gives error!!
}
The solution
const team = {
name: String,
members: [] as string[]
}
CodePudding user response:
One way is to specify the type of the whole object, just like you're doing with members - put the type of the object after a colon, before the = assignment:
const team: {
name: StringConstructor;
members: string[];
} = {
name: String,
members: [],
};
Another way is to assert the type of only the property in question with as (but I don't like this approach because I prefer to only use as to indicate to TypeScript something that there's no way of annotating otherwise).
const team = {
name: String,
members: [] as string[],
};
