The generated typescript looks redundant, but I'm sure it is not

NSwag generates typescript classes with properties defined as follows:

export class Foo {
  id?: number | undefined;
}

I know that ?means a property idis optional. I would expect these property definitions to be essentially the same as above:

id?: number
id: number | undefined

What are the differences between these definitions? Why did NSwag choose the first?

+4
source share
3 answers

Labeling a property with ?means that it can be declared or not declared on the object. Giving it a possible type undefinedsays that even if it is declared, it may not matter.

id?: number , , .

id: number | undefined , , , .

id?: number | undefined , , , .

obj = {id: undefined}, id , , obj = {}, id . typeof obj.id === 'undefined' true, id .

, Typescript, , . , , .

, , . , ? undefined, , , , . : typeof obj.id === 'number', (0 == false). (for i in obj) (if('id' in obj)) .

+2

, :

interface Foo {
    id?: number | undefined;
}

function giveMeFoo(foo: Foo): void {
    if ("id" in foo) {
        // Here, foo.id has type: number | undefined
    }
    if (foo.id) {
        // Here, foo.id has type: number
    }
}

interface Bar {
    id?: number;
}

function giveMeBar(bar: Bar): void {
    if ("id" in bar) {
        // Here, bar.id has type: number
    }
    if (bar.id) {
        // Here, bar.id has type: number
    }
}

, ( ?) , , , . ( ), undefined.

, , NSwag , id , id, undefined.

+2

The question mark icon will make this parameter optional by passing {} to what it expects the Foo object will not break in the TS compiler. If it is not optional and may be undefined, {} will cause a type error, but {id} not.

0
source

Source: https://habr.com/ru/post/1690634/


All Articles