Reputation: 3
Is there a way to only pass in one argument into args and let other values be default in TypeScript? I dont want "args = {}" and declaring defaults within the function due to intellisense.
function generateBrickPattern (
wallWidth: number,
wallHeight: number,
args = {
maxBrickWidth: 100,
maxBrickHeight: 50,
minBrickWidth: 50,
minBrickHeight: 25
}) {}
generateBrickPattern(500,500,{maxBrickWidth: 75}) //Prefered
generateBrickPattern(500,500,{maxBrickWidth: 75,
maxBrickHeight: 50,
minBrickWidth: 50,
minBrickHeight: 25}) //Not wanted
The prefered syntax gives the following error.
Argument of type '{ maxBrickWidth: number; }' is not assignable to parameter of type '{ maxBrickWidth: number; maxBrickHeight: number; minBrickWidth: number; minBrickHeight: number; }...'.
Upvotes: 0
Views: 65
Reputation: 73
You can do this by destructuring args
with default values:
function generateBrickPattern (
wallWidth: number,
wallHeight: number,
{
maxBrickWidth: maxBrickWidth = 100,
maxBrickHeight: maxBrickHeight = 50,
minBrickWidth: minBrickWidth = 50,
minBrickHeight: minBrickHeight = 25
} = {}
) {
console.log(maxBrickWidth);
}
If you don't want to destructure you could merge the provided args
with the defaults like this:
interface BrickPatternOptions {
maxBrickWidth: number;
maxBrickHeight: number;
minBrickWidth: number;
minBrickHeight: number;
}
function generateBrickPattern (
wallWidth: number,
wallHeight: number,
args: Partial<BrickPatternOptions> = {}
) {
const options: BrickPatternOptions = {
maxBrickWidth: 100,
maxBrickHeight: 50,
minBrickWidth: 50,
minBrickHeight: 25,
...args
};
console.log(options.maxBrickWidth);
}
Upvotes: 0
Reputation: 4353
You'll have to actually define the type for the last argument, and not let TypeScript infer it.
Try this:
interface BrickPatternOptions {
maxBrickWidth?: number;
maxBrickHeight?: number;
minBrickWidth?: number;
minBrickHeight?: number;
}
function generateBrickPattern (
wallWidth: number,
wallHeight: number,
args: BrickPatternOptions = {
maxBrickWidth: 100,
maxBrickHeight: 50,
minBrickWidth: 50,
minBrickHeight: 25
}) {}
Alternatively, you could also inline it if you wanted to:
function generateBrickPattern (
wallWidth: number,
wallHeight: number,
args: {
maxBrickWidth?: number,
maxBrickHeight?: number,
minBrickWidth?: number,
minBrickHeight?: number
} = {
maxBrickWidth: 100,
maxBrickHeight: 50,
minBrickWidth: 50,
minBrickHeight: 25
}) {}
Upvotes: 1