I am trying to avoid typing null checks for properties that are formerly optional on the outer interface, but are then assigned with default values for the whole context of the function body.
I used a type guard for it, the problem is that the guarded type is lost in a function, but not lost in an arrow function, even though it can't be hoisted before the type guard.
I don't want to introduce new variables for every function parameter in a similar manner and I don't want to call other functions with casting as printMenu(options as DefinedOptions).
TypeScript Version: 3.7.3, 3.8.0-beta
Search Terms:
typescript type guard function arrow function
Code
exportinterfaceOptions{header?: stringborder?: booleanpageSize?: numberhelpMessage?: stringshowKeypress?: boolean}interfaceDefinedOptionsextendsOptions{pageSize: numberhelpMessage: string}constisType=<T>(arg: any): arg is T=>trueexportdefaultasyncfunctionmenu(options: Options){options// Optionsoptions.pageSize=options.pageSize??0options.helpMessage=options.helpMessage??'Default message'if(!isType<DefinedOptions>(options))returnnulloptions// DefinedOptionsreturnnewPromise((resolve,reject)=>{functionhandleMenuKeypress(key: any){options// Options - should be DefinedOptionsprintMenu(options)// error}constcandleMenuKeypress=(key: any)=>{options// DefinedOptionsprintMenu(options)// no error}})}functionprintMenu(options: DefinedOptions){}Playground Link
Expected behavior:
Type should be DefinedOptions in both.
Actual behavior:
Type is Options in function but DefinedOptions in arrow function.
Related:
#10927
I am trying to avoid typing null checks for properties that are formerly optional on the outer interface, but are then assigned with default values for the whole context of the function body.
I used a type guard for it, the problem is that the guarded type is lost in a function, but not lost in an arrow function, even though it can't be hoisted before the type guard.
I don't want to introduce new variables for every function parameter in a similar manner and I don't want to call other functions with casting as
printMenu(options as DefinedOptions).TypeScript Version: 3.7.3, 3.8.0-beta
Search Terms:
typescript type guard function arrow function
Code
Playground Link
Expected behavior:
Type should be
DefinedOptionsin both.Actual behavior:
Type is
Optionsin function butDefinedOptionsin arrow function.Related:
#10927