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[]
}
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[],
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.