Reputation:
I am learning typescript Why does the array defining show error here? //tried (string | number)[]
interface IState {
orgTypes: Array<orgTypes>; //shows error here
orgType: string;
}
const data: IState = {
orgType: "",
orgTypes: [
{ id: "1", name: "Vendor" },
{ id: "2", name: "Supplier" },
{ id: "3", name: "Vendor and Supplier" }
]
};
Upvotes: 0
Views: 28
Reputation: 37594
There is no type orgTypes
, you declared it as a variable name. I guess you want to declare a type which you can like this
type orgs = {id: string, name: string}
interface IState {
orgTypes: Array<orgs>;
orgType: string;
}
Upvotes: 0
Reputation: 1074335
You're not defining a type called orgTypes
anywhere. From the question and comment, I suspect you want something like this:
// Define an `OrgType` type
interface OrgType {
id: string;
name: string;
}
// Define an `IState` type
interface IState {
orgTypes: OrgType[]; // Or Array<OrgType>; if you prefer, same thing
orgType: string;
}
// Define runtime data using those types
const data: IState = {
orgType: "",
orgTypes: [
{ id: "1", name: "Vendor" },
{ id: "2", name: "Supplier" },
{ id: "3", name: "Vendor and Supplier" }
]
};
(On the playground)
If you don't want to define an actual interface for OrgType
, that's fine, you can do it inline as well:
// Define an `IState` type
interface IState {
orgTypes: {id: string; name: string;}[];
orgType: string;
}
// Define runtime data using those types
const data: IState = {
orgType: "",
orgTypes: [
{ id: "1", name: "Vendor" },
{ id: "2", name: "Supplier" },
{ id: "3", name: "Vendor and Supplier" }
]
};
(On the playground)
But almost any time I see someone define something inline like that, they end up needing it again elsewhere, so...
Upvotes: 1