Optional Elements in Tuples
What
Like object properties or function parameters, tuple elements can be marked as optional.
How
You add a question mark (?) after the element’s name or type. All optional elements must come after the required elements:
type HttpResponse = [statusCode: number, data: string, error?: string];
const success: HttpResponse = [200, "OK"];
const fail: HttpResponse = [404, "", "Not Found"];
Why
Optional elements allow tuples to represent flexible data structures, such as an API response that may or may not include an error message. In TypeScript, an optional element is automatically unioned with undefined.
Summary
Use optional elements to handle varying lengths of positional data, but consider an object if the structure becomes too complex.