How to make optional properties to required based on a condition?Make all properties within a Typescript interface optionalHow do you explicitly set a new property on `window` in TypeScript?In a React/Redux project how to make Typescript aware of property passed by redux's connect decorator?Typescript async/await not workingRedux-Form v7 Field component typescript errorsAccess unitiliazied TypeScript fieldvue-property-decorator @Prop How to use interface to define an arrayHow to initialise interface properties in complex interfacesHow can I check that a string is a property a particular interface in TypeScriptProblems in switching to TypeScript in React applicationHow to obtain additional data from select options choice in React / Typescript app

What is the meaning of でも 私 あなたのそういうところ すきよ?

Low quality postdoc application and deadline extension

What is the difference between 「名前【なまえ】」 and 「名称【めいしょう】」?

Did the US Climate Reference Network Show No New Warming Since 2005 in the US?

Identifying the following distribution

Why does the UK Prime Minister need the permission of Parliament to call a general election?

How do I anonymously report the Establishment Clause being broken?

How do German speakers decide what should be on the left side of the verb?

Do I have to rename all creatures in a new world?

Is there a way to retrieve the “source code” and the argument pattern from a macro for reuse (i.e. what show shows)?

What's the point of this macro?

What are some countries where you can be imprisoned for reading or owning a Bible?

How can I implement regular expressions on an embedded device?

GFI outlets tripped after power outage

Are buttons really enough to bound validities by S4.2?

Bidirectional Dictionary

How can I oppose my advisor granting gift authorship to a collaborator?

Are there mathematical concepts that exist in the fourth dimension, but not in the third dimension?

Why is a pressure canner needed when canning?

Tying double knot of garbarge bag

split a six digits number column into separated columns with one digit

Why do old games use flashing as means of showing damage?

Numerical minimum of a one-valued function

Dissuading my girlfriend from a scam



How to make optional properties to required based on a condition?


Make all properties within a Typescript interface optionalHow do you explicitly set a new property on `window` in TypeScript?In a React/Redux project how to make Typescript aware of property passed by redux's connect decorator?Typescript async/await not workingRedux-Form v7 Field component typescript errorsAccess unitiliazied TypeScript fieldvue-property-decorator @Prop How to use interface to define an arrayHow to initialise interface properties in complex interfacesHow can I check that a string is a property a particular interface in TypeScriptProblems in switching to TypeScript in React applicationHow to obtain additional data from select options choice in React / Typescript app






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















Here is my code:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const name, parent = await createComponent();

console.log(parent.name);



I want to make parent optional property of IComponent interface to required property if the opts is existed in createComponent function.



For now, I got an error when I use parent.name in main function.




Object is possibly 'undefined'.ts(2532)




I want the return value's interface of createComponent function to be like: Promise<IComponentRequired> if opts is existed and return Promise<IComponent> if opts is not existed. which like this:



interface IComponentRequired 
name: string;

parent: name: string ;



My thinking is IComponent => Required<T> => IComponentRequired.



update



Here is my try, but didn't work.



async function otherMain() 
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);



Got error:




Type 'IComponent' is not assignable to type 'Required'.
Types of property 'parent' are incompatible.
Type ' name: string; | undefined' is not assignable to type ' name: string; '.
Type 'undefined' is not assignable to type ' name: string; '.ts(2322)











share|improve this question


























  • possible duplicate of : stackoverflow.com/questions/39713349/…

    – Azeem Aslam
    Mar 28 at 4:27

















1















Here is my code:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const name, parent = await createComponent();

console.log(parent.name);



I want to make parent optional property of IComponent interface to required property if the opts is existed in createComponent function.



For now, I got an error when I use parent.name in main function.




Object is possibly 'undefined'.ts(2532)




I want the return value's interface of createComponent function to be like: Promise<IComponentRequired> if opts is existed and return Promise<IComponent> if opts is not existed. which like this:



interface IComponentRequired 
name: string;

parent: name: string ;



My thinking is IComponent => Required<T> => IComponentRequired.



update



Here is my try, but didn't work.



async function otherMain() 
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);



Got error:




Type 'IComponent' is not assignable to type 'Required'.
Types of property 'parent' are incompatible.
Type ' name: string; | undefined' is not assignable to type ' name: string; '.
Type 'undefined' is not assignable to type ' name: string; '.ts(2322)











share|improve this question


























  • possible duplicate of : stackoverflow.com/questions/39713349/…

    – Azeem Aslam
    Mar 28 at 4:27













1












1








1








Here is my code:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const name, parent = await createComponent();

console.log(parent.name);



I want to make parent optional property of IComponent interface to required property if the opts is existed in createComponent function.



For now, I got an error when I use parent.name in main function.




Object is possibly 'undefined'.ts(2532)




I want the return value's interface of createComponent function to be like: Promise<IComponentRequired> if opts is existed and return Promise<IComponent> if opts is not existed. which like this:



interface IComponentRequired 
name: string;

parent: name: string ;



My thinking is IComponent => Required<T> => IComponentRequired.



update



Here is my try, but didn't work.



async function otherMain() 
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);



Got error:




Type 'IComponent' is not assignable to type 'Required'.
Types of property 'parent' are incompatible.
Type ' name: string; | undefined' is not assignable to type ' name: string; '.
Type 'undefined' is not assignable to type ' name: string; '.ts(2322)











share|improve this question
















Here is my code:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const name, parent = await createComponent();

console.log(parent.name);



I want to make parent optional property of IComponent interface to required property if the opts is existed in createComponent function.



For now, I got an error when I use parent.name in main function.




Object is possibly 'undefined'.ts(2532)




I want the return value's interface of createComponent function to be like: Promise<IComponentRequired> if opts is existed and return Promise<IComponent> if opts is not existed. which like this:



interface IComponentRequired 
name: string;

parent: name: string ;



My thinking is IComponent => Required<T> => IComponentRequired.



update



Here is my try, but didn't work.



async function otherMain() 
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);



Got error:




Type 'IComponent' is not assignable to type 'Required'.
Types of property 'parent' are incompatible.
Type ' name: string; | undefined' is not assignable to type ' name: string; '.
Type 'undefined' is not assignable to type ' name: string; '.ts(2322)








typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 4:28







slideshowp2

















asked Mar 28 at 4:22









slideshowp2slideshowp2

4,1465 gold badges40 silver badges101 bronze badges




4,1465 gold badges40 silver badges101 bronze badges















  • possible duplicate of : stackoverflow.com/questions/39713349/…

    – Azeem Aslam
    Mar 28 at 4:27

















  • possible duplicate of : stackoverflow.com/questions/39713349/…

    – Azeem Aslam
    Mar 28 at 4:27
















possible duplicate of : stackoverflow.com/questions/39713349/…

– Azeem Aslam
Mar 28 at 4:27





possible duplicate of : stackoverflow.com/questions/39713349/…

– Azeem Aslam
Mar 28 at 4:27












1 Answer
1






active

oldest

votes


















0
















You can use overloads to either return the required version or the one where the property is optional:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);






share|improve this answer

























  • Thanks. Second error gone. But the first error still there. It seems make sense.

    – slideshowp2
    Mar 28 at 7:03











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390133%2fhow-to-make-optional-properties-to-required-based-on-a-condition%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0
















You can use overloads to either return the required version or the one where the property is optional:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);






share|improve this answer

























  • Thanks. Second error gone. But the first error still there. It seems make sense.

    – slideshowp2
    Mar 28 at 7:03
















0
















You can use overloads to either return the required version or the one where the property is optional:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);






share|improve this answer

























  • Thanks. Second error gone. But the first error still there. It seems make sense.

    – slideshowp2
    Mar 28 at 7:03














0














0










0









You can use overloads to either return the required version or the one where the property is optional:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);






share|improve this answer













You can use overloads to either return the required version or the one where the property is optional:



interface IOptions 
clientId: string;
token: string;


interface IComponent
name: string;

parent?: name: string ;


async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent>
const component: IComponent = name: '' ;

if (opts)
component.parent = name: `$opts.clientId-$opts.token` ;


return component;


async function main()
const opts: IOptions = clientId: '123', token: '321' ;
const component: Required<IComponent> = await createComponent(opts);

console.log(component.parent.name);







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 28 at 6:03









Titian Cernicova-DragomirTitian Cernicova-Dragomir

94.4k5 gold badges82 silver badges100 bronze badges




94.4k5 gold badges82 silver badges100 bronze badges















  • Thanks. Second error gone. But the first error still there. It seems make sense.

    – slideshowp2
    Mar 28 at 7:03


















  • Thanks. Second error gone. But the first error still there. It seems make sense.

    – slideshowp2
    Mar 28 at 7:03

















Thanks. Second error gone. But the first error still there. It seems make sense.

– slideshowp2
Mar 28 at 7:03






Thanks. Second error gone. But the first error still there. It seems make sense.

– slideshowp2
Mar 28 at 7:03









Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390133%2fhow-to-make-optional-properties-to-required-based-on-a-condition%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript