

Picture by the writer
. Introduction
You’ve been coding in Azar for a while, he likes it, and maybe you can write decoration in your sleep. But your head has a wonderful voice that you should learn a type script. It may be for this complete stack character, or maybe you are tired of telling why the big code is “right” for the base.
The thing is: Type script is not just “JavaScript” with type. This is what the Javascript should have been from the beginning. And if you are coming from, you have already understood more than your idea.
. Go to a type script from azagar
Giving you duck typing and dynamic flexibility. The type script gives you the same flexibility with a protective trap. Think about it The mape of the tiger If Mipi actually worked everywhere.
In this way, you can call on anything on any way and it works “hope”. Type script tells you on time that it will work, will save you from them "AttributeError: 'NoneType' object has no attribute 'name'" Moments
# Python: You hope this works
def process_user(user):
return user.name.upper()
// TypeScript: You know this works
function processUser(user: User): string {
return user.name.toUpperCase();
}Unless user Is not A name Property, type script catchs it before your code runs. So you don’t need defense if hasattr(obj, 'attribute') Check everywhere
. The basics of a type script
Let’s start with the basics of type script.
!! Variable and basic types
The types of indicators are optional suggestions. Types of type scripts are like more enforced contracts. Good news? The type script can mostly evaluate the types, so you don’t have to explain everything.
# Python
name = "Alice"
age = 30
is_active = True
scores = (95, 87, 92)
user = {"name": "Bob", "age": 25}
// TypeScript
const name = "Alice"; // string (inferred)
const age = 30; // number (inferred)
const isActive = true; // boolean (inferred)
const scores = (95, 87, 92); // number() (inferred)
const user = { name: "Bob", age: 25 }; // object (inferred)
// Or be explicit
const name: string = "Alice";
const scores: number() = (95, 87, 92);You only need clear explanations when it is not clear or when you want to be extra clear about your intentions.
!! Functions
The function syntax map almost directly maps, but the type script’s approach to default parameters is clearly compared to the variable default argument guts.
# Python
def greet(name: str, excited: bool = False) -> str:
suffix = "!" if excited else "."
return f"Hello, {name}{suffix}"
// TypeScript
function greet(name: string, excited = false): string {
const suffix = excited ? "!" : ".";
return `Hello, ${name}${suffix}`;
}
// Or arrow function (Python lambda equivalent)
const greet = (name: string, excited = false): string =>
`Hello, ${name}${excited ? "!" : "."}`;The arrow function is similar to the syntax of the syntax, but is more powerful. You can write a full function body or a comprehensive one liner. Template Literals (they back tux) work exactly the same F. Strings of Azigar.
!! Class
Type script classes feel more smooth than the classes. No more self Everywhere, and the conductor parameters can automatically become features.
# Python
class User:
def __init__(self, name: str, email: str):
self.name = name
self.email = email
def greet(self) -> str:
return f"Hi, I'm {self.name}"
// TypeScript
class User {
constructor(public name: string, public email: string) {}
greet(): string {
return `Hi, I'm ${this.name}`;
}
}They public The key word in the converter is the short hand of the type script “automatically make this property and assign it to the parameter.” So you don’t have to use self.name = name Boiler plate you can also use private Or protected for encapsulation.
. Where the type script gets interesting
This is the place where you move beyond the basics to make the type script feel interesting.
!! Types of the Union (of Azigar Union But better)
The type of module is the type of union, but they are sometimes verbs. Types of the type script union are made in language.
# Python
from typing import Union
def process_id(user_id: Union(str, int)) -> str:
return str(user_id)
// TypeScript
function processId(userId: string | number): string {
return userId.toString();
} | The syntax is more clearer than Union(str, int)And the type script can be more sophisticated. It knows what methods are available on a specific type of run time.
!! Literal types
The literal types of Azgar are relatively new but helpful. Type script, however, has more effective literal types.
# Python
from typing import Literal
Status = Literal("pending", "approved", "rejected")
def update_status(status: Status) -> None:
print(f"Status: {status}")
// TypeScript
type Status = "pending" | "approved" | "rejected";
function updateStatus(status: Status): void {
console.log(`Status: ${status}`);
}Try to pass the wrong string like “perhaps” updateStatusAnd will refuse to set the type script. Even your editor will automatically provide for the correct options. It is like an anoma that is really useful.
!! Interface
The deduction of the degree to make structural data are very good:
# Python
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
age: intBut the interface in the type script is more flexible. They explain the data without creating a particular class process.
// TypeScript
interface User {
name: string;
email: string;
age: number;
}
// Use it anywhere
const user: User = { name: "Alice", email: "alice@example.com", age: 30 };Any item that has the right features automatically satisfy the interface. No need for inheritance, no clear class institute is required. This is duck typing with time verification of time.
. Learning more type script features
Now learn some more useful features of the type script.
!! Generic (such as azar TypeVarJes
The typical typing of Azigar works, but it is low. Types scripts feel natural and powerful outside the genes box.
# Python
from typing import TypeVar, List
T = TypeVar('T')
def first(items: List(T)) -> T:
return items(0)
// TypeScript
function first(items: T()): T {
return items(0);
}
// Works with anything
const firstNumber = first((1, 2, 3)); // number
const firstString = first(("a", "b", "c")); // string The type script automatically leads to general type. Call first With numbers, and it returns a number. Call it with a wire, and it returns the wire. No clear type of parameters are needed, but when you are not clear, you can provide them.
!! Type the guards
Type Guards allow you to write a run time check that the compiler considers and uses for narrow types in the subsequent code.
function isString(value: unknown): value is string {
return typeof value === "string";
}
function processValue(value: string | number) {
if (isString(value)) {
return value.toUpperCase();
}
return value.toFixed(2);
} value is string The syntax tells the type script that if this function returns correctly, the parameter is definitely a wire. If inside the block, you get the fully wire and features of the wire. Based on your run -time checks, no minerals, no claims, simply tighten smart type.
!! MAPED TYPESS (List of understanding for Types)
Think about the list of meped types as a sense of understanding, but the kind of changes. They allow you to change the current things and create new types.
type User = {
name: string;
email: string;
age: number;
};
// Make all properties optional
type PartialUser = Partial;
// Make all properties readonly
type ReadonlyUser = Readonly;
// Pick specific properties
type UserContact = Pick; These types of utility ship ship with type script and solve joint patterns. If you need some kind of a user like the user but with optional fields for updates, you can use Partial. And if you need to ensure no modification after creation, use Readonly.
. Error in handling in type script
Developers like to try/like the blocks, but they can get the function. Type scripts uses a different approach using the results of the results and the types of union of the results that clarify the errors in your function signatures:
// Result type pattern (inspired by Rust)
type Result = { success: true; data: T } | { success: false; error: E };
// Make this file a module
export {};
// Assuming you have a User type and parseUser function
interface User {
name: string;
// ... other properties
}
function parseUser(data: unknown): User {
// Your parsing logic here
// This should throw an error if parsing fails
if (!data || typeof data !== 'object') {
throw new Error('Invalid user data');
}
const user = data as any;
if (!user.name || typeof user.name !== 'string') {
throw new Error('User name is required and must be a string');
}
return { name: user.name };
}
async function safeParseUser(data: unknown): Promise> {
try {
const user = parseUser(data);
return { success: true, data: user };
} catch (error) {
// Fix: Handle the case where error might not have a message property
const errorMessage = error instanceof Error ? error.message : String(error);
return { success: false, error: errorMessage };
}
} You can use it like this:
// Usage (wrapped in an async function or use at top level in a module)
async function example() {
const rawData = { name: "John Doe" }; // Example data
const result = await safeParseUser(rawData);
if (result.success) {
console.log(result.data.name); // TypeScript knows this is User
} else {
console.error(result.error); // TypeScript knows this is string
}
}
// Call the example function
example();This sample illustrates errors in the type system. Instead of flying hidden, mistakes become part of the return type. Result Type is forcing you to handle both success and failure matters. Discrimination unions of the type script make this sample easier: Success property suggests which branch you are in the union, so it knows whether data or error is available.
. Conclusion
Type script web development, large -scale applications, and anywhere you need to be strong APIS.
The transfer is not about learning a new language. It’s about using everything that you find in different ecosystem about good software design. Clean codes, read -to -reads, and thinking of you for deliberate abstract translates directly.
So open the VS code, make a .ts File, and start coding. The worst thing that happens? You learn something new. The best thing? You can find your new favorite language. Happy coding!
Pray Ca Is a developer and technical author from India. She likes to work at the intersection of mathematics, programming, data science, and content creation. The fields of interest and expertise include dupas, data science, and natural language processing. She enjoys reading, writing, coding and coffee! Currently, they are working with the developer community to learn and share their knowledge with the developer community by writing a lesson, how to guide, feed and more. The above resources review and coding also engages lessons.