Question mark Typescript variable

前端 未结 3 635
闹比i
闹比i 2021-01-17 22:04

I\'ve seen code snippets like these:

export interface IUser {
    email?: string;
    firstName?: string;
    lastName?: string;
}

But why

相关标签:
3条回答
  • 2021-01-17 22:43

    In TypeScript, <name>?: <typename> a shorthand for <name>: <typename> | undefined.

    This indicates to the type system that a symbol may contain a value of the indicated type or it may contain the value undefined (which is like null).

    This is important when the (new in TypeScript 2) --strictNullChecks option is enabled. The documentation on Null- and undefined-aware types option is probably where you should start to understand why this is useful.

    0 讨论(0)
  • 2021-01-17 22:47

    If I am not mistaked, its to indicate that its optional, that means that it can be null.

    0 讨论(0)
  • 2021-01-17 22:56

    It means they can be there but dont have to be. It allows for optional field names. It can be quite common to use.

    An example use is allowing users on a website to have an optional display name.

    0 讨论(0)
提交回复
热议问题