0
interface IPrintConfig {
    name: string;
    copies: number;
}

function print(config: IPrintConfig = {}) {
    console.log(`Print ${config.copies} on printer ${config.name}`);
}

print();

enter image description here

when nothing it passed to print() i made the default value as {}. But print() is expecting a value of type IPrintConfig which comntains name and copies properties. I can solve this issue by making both of those properties as optional. Is there another way to solve this issue without making them optional

1
  • What values do you want config.copies and config.name to have inside the implementation if someone just calls print()? Commented Jul 10, 2019 at 18:19

2 Answers 2

4

Option 1

Make your interface values optional using a ?:

interface IPrintConfig {
    name?: string;
    copies?: number;
}

function print(config: IPrintConfig = {}) {
    console.log(`Print ${config.copies} on printer ${config.name}`);
}

Option 2

Make the parameter optional instead of predefined:

function print(config?: IPrintConfig) {
  if(config)
    console.log(`Print ${config.copies} on printer ${config.name}`);
  else
    console.log(`No value passed`);
}

Option 3

Set the default values:

function print(config: IPrintConfig = {name: '', copies: -1}) {
    console.log(`Print ${config.copies} on printer ${config.name}`);
}

Option 4

Require that the parameter be passed to the function:

function print(config: IPrintConfig) {
    console.log(`Print ${config.copies} on printer ${config.name}`);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, you wouldn't assign a default value.
0

What if you make param optional?

interface IPrintConfig {
    name: string;
    copies: number;
}

function print(config?: IPrintConfig) {
    config  && console.log(`Print ${config.copies} on printer ${config.name}`);
}

print();

8 Comments

What do you intend config?.properties to mean? That's not valid TypeScript or JavaScript syntax, as far as I know
Indeed it is a valid operator in TypeScript, and called optional chaining
The exclamation point is valid though config!.properties might mean something different though
config!.properties will throw a runtime exception if config is not defined, so you don't want to do that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.