0

Having such simple JS objects definitions:

...
const Post1 : TPost = {
    title: "Post One",
    body: "This is the Post One"
}

const Post2 : TPost = {
    title: "Post Two",
    body: "This is the Post Two"
}
...

and such TyprScript TPost type definition:

interface TPost  { 
    title: string,
    body: string
}

One can define a TPosts type like that

type TPosts = TPost[];

My question is how to do that - define TPosts as an array of TPost objects using the Interface syntax?

1
  • 4
    type TPosts = TPost[]; is correct for making TPosts an array of TPost. So, I'm not sure I understand the question. Note that normally you don't declare a type for an array of something, the notation X[] is most often used. Not necessarily for technical reasons but it does make it easier to understand what the type is without needing to look it up, if you see Xs you won't necessarily know it's an array of X. Commented Feb 8, 2021 at 9:10

3 Answers 3

3

You can just do

const TPosts: TPost[] = [
    Post1,
    Post2,
]

Specifying array types for variables is the same as for normal variables, you only need to add [].

Sign up to request clarification or add additional context in comments.

1 Comment

Ok Bob, but I'd like to specify that the TPosts type is an array of objects of type TPost, not just array of concrete instances Post1 & Post2. I'd like to be more generic/universal with the TPosts definition.
1

i don't know your usecase but i guess this should help.

interface TPost  { 
    title: string,
    body: string
}

const tposts: TPost[] = [
    {
    title: "Post One",
    body: "This is the Post One"
    },
    {
    title: "Post Two",
    body: "This is the Post Two"
    },
]

1 Comment

array of objects of type TPost, not just array of concrete instances Post1 & Post2. I'd like to be more generic/universal with the TPosts definition.
0

I'm not sure this is what you're looking for but here it is:

interface TPosts {
    tposts: TPost[]
}

Still I think this is not a good way to approach...

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.