- Technicalpig
- Posts
- TechnicalPigđ·: Top 5 TypeScript Tips That Helped Me Advance from Junior to Mid-Level Engineer
TechnicalPigđ·: Top 5 TypeScript Tips That Helped Me Advance from Junior to Mid-Level Engineer
In this newsletter, I outline five essential TypeScript (TS) tips that were key in my transition from a junior to a mid-level engineer.
These practical, tried-and-tested insights have not only enhanced my coding skills but also deepened my understanding of TypeScript. Each tip comes from real-world experience and is designed to provide you with actionable knowledge that you can use for your development.
1. Actually understand how TS is difference from JS
TS checks types at compile time unlike JS that checks types at runtime when the code runs and not before.
TS is a superset of JS, which means that any valid JS code is also valid TS code. TS is a superset because it adds static typing capabilities to JS.
How is this beneficial? TS helps catch type errors early in the development process potentially saving time and reducing runtime errors. For example, if a function expects a number by you pass it a string, JS will throw an error when that function is actually called. Whereas TS will catch the error at compile time, before the code is run.
2. Type literals
Type literals in TS is a powerful feature that allows you to define types using the actual value themselves instead of basic types like number
and string
.
This ability reduces the changes of bugs because you can enforce specific values rather than broader types.
Example: If you're defining a configuration option that should only accept "yes" or "no" as valid inputs, using type literals prevents any other strings from being accidentally passed or set.
// Define the type using type literals
type Answer = "yes" | "no";
// Function to set the configuration option with type checking
function setConfigOption(answer: Answer): void {
console.log(`Configuration set to: ${answer}`);
}
// Example usage
setConfigOption("yes"); // This will work
setConfigOption("no"); // This will work
// The following line will cause a TypeScript error because it is not a valid 'Answer'
// setConfigOption("maybe");
3. Index signatures
Index signatures are useful when you are working with objects where you donât know all the property names at compile time, but you do know the shape of the value associated with those keys.
The keys in index signatures can be either strings or numbers. This matches JSâs fundamental property key types, as these are the only types allowed for object keys.
Benefits? Even thought the object properties are dynamic, TS ensures that the values assigned to those properties adhere to a specific type thus preserving the benefits of static type checking.
Practical Use: Index signatures are useful when you are working with configuration objects where the property keys are determined by user input or external data..
interface StringIndexedItems {
[key: string]: number; // Index signature
}
const data: StringIndexedItems = {
apples: 10,
oranges: 20
};
data.pears = "fifteen"; // Error: Type 'string' is not assignable to type 'number'.
data.pears = 15; // correct
4. Avoid empty object type
Avoid empty object type whenever possible. This is because every type, except for null
and undefined
, is assignable to an empty object type.
An empty object type {}
effectively means "an object with zero or more properties of any typeâ.
This sacrifices the type safety benefits of TS.
5. Union type
Union type isnât necessarily one specific member of your union, it can be both members at once.
Union types do not require an object to exclusively match one type or another - the object can have a mix of properties from any of the types in the union.
type Cat = {
name: string,
purrs: boolean
}
type Dog = {
name: string,
barks: boolean
}
type UnionCatDog = Cat | Dog
const hybridCatDog: UnionCatDog = {
name: 'hybrid',
purrs: true,
barks: true
}
This is because TS uses a structural type system which means it focuses on the shape that values have. If the shape of the object can match any one of the types in the union at least partially (considering optional properties and their types), the object is considered compatible.
Summary
I hope you find these TS tips useful for your own programming journey!
These are tips I picked up from the book âProgramming TypeScript: Making your JavaScript Application Scaleâ. I found it particularly insightful as someone who works mostly on JS apps. It helped me understand best practices when using TS which I could apply to my work.