user11679005
user11679005

Reputation:

I am learning typescript Why does the array defining show error here?

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

Answers (2)

Murat Karag&#246;z
Murat Karag&#246;z

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

T.J. Crowder
T.J. Crowder

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

Related Questions