@@ -37,6 +37,12 @@ namespace ts.codefix {
3737
3838 type AddNode = PropertyDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction ;
3939
40+ export const enum PreserveOptionalFlags {
41+ Method = 1 << 0 ,
42+ Property = 1 << 1 ,
43+ All = Method | Property
44+ }
45+
4046 /**
4147 * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`.
4248 * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub.
@@ -50,6 +56,7 @@ namespace ts.codefix {
5056 importAdder : ImportAdder | undefined ,
5157 addClassElement : ( node : AddNode ) => void ,
5258 body : Block | undefined ,
59+ preserveOptional = PreserveOptionalFlags . All ,
5360 isAmbient = false ,
5461 ) : void {
5562 const declarations = symbol . getDeclarations ( ) ;
@@ -83,7 +90,7 @@ namespace ts.codefix {
8390 /*decorators*/ undefined ,
8491 modifiers ,
8592 name ,
86- optional ? factory . createToken ( SyntaxKind . QuestionToken ) : undefined ,
93+ optional && ( preserveOptional & PreserveOptionalFlags . Property ) ? factory . createToken ( SyntaxKind . QuestionToken ) : undefined ,
8794 typeNode ,
8895 /*initializer*/ undefined ) ) ;
8996 break ;
@@ -158,14 +165,14 @@ namespace ts.codefix {
158165 }
159166 else {
160167 Debug . assert ( declarations . length === signatures . length , "Declarations and signatures should match count" ) ;
161- addClassElement ( createMethodImplementingSignatures ( checker , context , enclosingDeclaration , signatures , name , optional , modifiers , quotePreference , body ) ) ;
168+ addClassElement ( createMethodImplementingSignatures ( checker , context , enclosingDeclaration , signatures , name , optional && ! ! ( preserveOptional & PreserveOptionalFlags . Method ) , modifiers , quotePreference , body ) ) ;
162169 }
163170 }
164171 break ;
165172 }
166173
167174 function outputMethod ( quotePreference : QuotePreference , signature : Signature , modifiers : NodeArray < Modifier > | undefined , name : PropertyName , body ?: Block ) : void {
168- const method = createSignatureDeclarationFromSignature ( SyntaxKind . MethodDeclaration , context , quotePreference , signature , body , name , modifiers , optional , enclosingDeclaration , importAdder ) ;
175+ const method = createSignatureDeclarationFromSignature ( SyntaxKind . MethodDeclaration , context , quotePreference , signature , body , name , modifiers , optional && ! ! ( preserveOptional & PreserveOptionalFlags . Method ) , enclosingDeclaration , importAdder ) ;
169176 if ( method ) addClassElement ( method ) ;
170177 }
171178 }
0 commit comments