2

I have this List object, but later on the shape changed, I need an extra id property, but how to not modify List?

interface List {
    name: string //without adding id here
}

interface ListData {
    type: string
    lists: List[] //how to include id here?
}

const data: ListData = {
    type: 'something',
    lists: [{
        id: '1',
        name: 'alice'
    }, {
        id: '2',
        name: 'ja'
    }]
}

3 Answers 3

1

You can extend the List interface

interface List {
  name: string //without adding id here
}

interface ListId extends List {
  id: string
}

interface ListData {
  type: string
  lists: ListId[]
}

const data: ListData = {
  type: 'something',
  lists: [{
    id: '1',
    name: 'alice'
  }, {
    id: '2',
    name: 'ja'
  }]
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can use extends keyword for extend existing interface

interface ListWithId extends List {
  id: string;
}

or you can make id optional in existing List interface so if you already used it some where it was not affect any one.

interface List {
  name: string;
  id?: string;
}

Note: ? is used to make property optional.

Comments

1

to add alternative approach to previous answers

type ListWithId = List & {id: string};

interface ListData {
    type: string
    lists: ListWithId[] //how to include id here?
}

or, not pretty but works

interface ListData {
    type: string
    lists: (List & {id: string})[] //how to include id here?
}

1 Comment

I like the non pretty approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.