Home > Net >  About typescript define an object who has not contain a field the type defined
About typescript define an object who has not contain a field the type defined

Time:12-09

Assume I have an interface Book:

interface Book {
    id: number
    info: {
        name: string,
    }
}

Now I define a list named bookList:

const bookList: Book[] = [
    {
        id: 1,
        info: {
            name: 'bookA',
        }
    },
    {
        id: 2
    }
]

Absolutely I will get an error like this:

Property 'info' is missing in type '{ id: number; }' but required in type 'Book'.

Then I add a ? to the Book like this:

interface Book {
    id: number
    info?: {
        name: string,
    }
}

The error will gone.

But when I get name like below:

console.log('book name', bookList[0].info.name)

Here comes another error:

Object is possibly 'undefined'.

Of cause I can do like this: bookList[0].info!.name or bookList[0].info?.name But I have multiple code like bookList[0].info.name, I don't want to add ! or ? everywhere.

Could someone please kindly suggest me how to solve this?

Here is the Typescript Playground

CodePudding user response:

That's right becase info property is possibly undefiend you can have question mark by using that, like this :

console.log('book name', bookList[0].info?.name)

CodePudding user response:

One way would be to put ! after info. console.log('book name', bookList[0].info!.name)

Note: ! operator tells the compiler to ignore the possibility of it being undefined.

  • Related