💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.
Tuple is TypeScript Specific thing and we don’t have tuples in JavaScript. Tuples allow us to enforce order of types in an array.
let UserTuple: [number,string,boolean]
UserTuple = [122,"Palash",true] // valid
UserTuple = [122,"Palash","true"] // not valid
We can define tuples using type as well
type UserTuple = [number,string,boolean] // using type to define tuple
let UserTuple2: UserTuple = [122,"Palash",true] // valid
let UserTuple3: UserTuple = [122,"Palash","true"] // not valid
Bad behavior
Tuple has some bad behavior which it should not do but it is allowed anyways.
// bad behaviour
let UserTuple: UserTuple = [122,"Palash",true]
// since user tuple is just an array we can use array methods on it.
// which should not happen because the purpose of tuple is to make
// sure we have all the menthioned data types in order
UserTuple.push("tf")
if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!