0

Is it possible to do something like this to define a custom Companies Array type?:

export interface Company {
  name: string;
}

export interface Companies: Array<Company> {

}

it doesn't seem to like my syntax for Companies.

Or does this not make any sense to try to do at all?

7
  • 2
    is this what you mean interface Companies extends Array<Company> {}? Commented Sep 27, 2020 at 7:00
  • 6
    You could go with alias: type Companies = Array<Company>; Commented Sep 27, 2020 at 7:02
  • 1
    maybe, that's probably what I infer. I guess making this would allow my TS to be a little shorter than specifying Array<Company> all over the place in my code? Commented Sep 27, 2020 at 7:02
  • it sounds like both of you are showing me a way to basically kinda do the same thing right? And benefit being that it's cleaner to use in my code as well when I use that type or interface rather than specify Array<Company> all over the place right? Commented Sep 27, 2020 at 7:04
  • 3
    just in case you want to have a shorter definition, you may go with Company[] Commented Sep 27, 2020 at 8:29

1 Answer 1

1

If you simply want an array of companies, you can use either one of these:

type Companies = Company[]
type Companies = Array<Company>

Alternatively, you don't even need to define a type alias and can just use Company[] or Array<Company>.

However, if you want to declare additional properties on the array, you can extend Array<Company>:

interface Companies extends Array<Company> {
  foo: string
  bar: number
}

To make such an object, you can use one of these:

declare const normalArray: Company[]

const companies1: Companies = Object.assign(normalArray, {foo: '', bar: 0})

const companies2 = normalArray as Companies
companies2.foo = ''
companies2.bar = 0
Sign up to request clarification or add additional context in comments.

Comments

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.