lch
lch

Reputation: 4931

Typescript: default value of function parameter missing required properties

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

Upvotes: 0

Views: 1529

Answers (2)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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}`);
}

Upvotes: 4

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

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();

Upvotes: 0

Related Questions