TS2706

error TS2706: Required type parameters may not follow optional type parameters.

Broken Code ❌

1
2
3
4
5
6
class KeyValuePair<Key = string, Value> {
key: Key | undefined;
value: Value | undefined;
}

const populationFigures = new KeyValuePair<string, number>();

Fixed Code ✔️

The generic type Key is defined with a default value of string which makes this type parameter not optional. However, the Value type parameter is optional and optional parameters are not allowed to follow required parameters.

To solve the situation, we have can switch the position of the two parameters which would impact how we use the code:

1
2
3
4
5
6
class KeyValuePair<Value, Key = string> {
key: Key | undefined;
value: Value | undefined;
}

const populationFigures = new KeyValuePair<number, string>();

Alternatively, we can also set a default type for Value:

1
2
3
4
5
6
class KeyValuePair<Key = string, Value = string> {
key: Key | undefined;
value: Value | undefined;
}

const populationFigures = new KeyValuePair<string, number>();