alif
alif

Reputation: 33

Create custom type for an array

I am using Typescript with Redux and want to put a type for initial state.

Examples I have seen assume initial state is key value pairs like:

const INITIAL_STATE: State = {
    id: '1',
    firstName: 'Michael',
    lastName: 'Black',
  }

where the type is defined as

export interface State {
  id: string
  firstName: string
  lastName: string
}

How about if the type is defined as

const INITIAL_STATE: State = [
  {
    id: '1',
    firstName: 'Michael',
    lastName: 'Black',
  },
  {
    id: '2',
    firstName: 'Tony',
    lastName: 'Montana',
  }
]

How would the type definition look? I did try look for answer as it looks like it should be simple to do but couldn't find anything...

Edit:

I guess I could do

const INITIAL_STATE: Array<State> = [
  {
    id: '1',
    firstName: 'Michael',
    lastName: 'Black',
  },
  {
    id: '2',
    firstName: 'Tony',
    lastName: 'Montana',
  }
]

But how about if I wanted a new definition, CustomerState?

Something like

export interface CustomerState Array<State>

which is a syntax error of course.

Upvotes: 1

Views: 65

Answers (1)

basarat
basarat

Reputation: 276373

export interface CustomerState Array

I would

export interface Person {
  id: string
  firstName: string
  lastName: string
}
export type State = Person[];
const INITIAL_STATE: State = [
  {
    id: '1',
    firstName: 'Michael',
    lastName: 'Black',
  },
  {
    id: '2',
    firstName: 'Tony',
    lastName: 'Montana',
  }
]

Upvotes: 2

Related Questions