TS1016

error TS1016: A required parameter cannot follow an optional parameter.

Broken Code ❌

1
2
3
function createUser(firstName: string, lastName: string, middleName?: string, age: number) {
// ...
}

Fixed Code ✔️

The easiest way to fix the error is to make age optional as well:

1
2
3
function createUser(firstName: string, lastName: string, middleName?: string, age?: number) {
// ...
}

Alternatively, you can flip the order of middleName and age. Be aware that this breaks the contract (signature) of the function and is considered a “breaking change”:

1
2
3
function createUser(firstName: string, lastName: string, age: number, middleName?: string) {
// ...
}

You could also make middleName non-optional:

1
2
3
function createUser(firstName: string, lastName: string, middleName: string, age?: number) {
// ...
}

Yet another solution would be to assign a default value to middleName so it won’t be optional by default. This allows age to be optional then:

1
2
3
function createUser(firstName: string, lastName: string, middleName: string = '', age?: number) {
// ...
}