0

I've been going through the typescript documentation for quite some time and I can't seem to find any examples regarding the below example for a type alias. I'm trying to understand what the purpose of the empty array is after the closing object brace.

Thanks!

type PostsProps = {
  posts: {
    tags?: {
      name: string
      slug: string
    }[] // what is the purpose of this empty array
  }[] // what is the purpose of this empty array
}

2 Answers 2

2

You can use an empty array to define an array type.

The empty array in the example code above basically defines the type of posts as an array of object(s) with a property of tags nested as another array of object(s) where there's name and slug properties which are both strings.

A simpler example, I could define a type for an array of strings like this

let color: string[];

color = ['red', 'green', 'more colors']; // This is ok

color = ['red', 'green', 5]; // This would flag
Sign up to request clarification or add additional context in comments.

2 Comments

It might be useful to point out that a type like Foo[] is shorthand for Array<Foo>, and the only time [] is interpreted as an "empty array" is when it stands on its own, as the empty tuple type.
Thanks. That is what I figured but wasn't sure. I usually would have factored out Tags and Posts into their own type alias or interface and explicitly declared the array type inside the type alias.
0

[] is special shorthand syntax for the Array type. So for example, string[] and Array<string> are equivalent.

A common code style is to use the short version for simple array types like number[], string[] or any[] while using Array for more complex types like Array<Record<string, string>>. However, as far as I know, TypeScript always displays the short syntax (in this case Record<string, string>[]) when you hover over the type.

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.