TS1016
A required parameter cannot follow an optional parameter.
Broken Code ❌
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:
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":
function createUser(firstName: string, lastName: string, age: number, middleName?: string) {
// ...
}You could also make middleName non-optional:
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:
function createUser(firstName: string, lastName: string, middleName: string = '', age?: number) {
// ...
}