Tuesday, October 7, 2025
HomeArtificial IntelligenceA Mild Introduction to TypeScript for Python Programmers

A Mild Introduction to TypeScript for Python Programmers

A Mild Introduction to TypeScript for Python ProgrammersA Mild Introduction to TypeScript for Python Programmers
Picture by Creator

 

Introduction

 
You’ve got been coding in Python for some time, completely like it, and may most likely write decorators in your sleep. However there’s this nagging voice in your head saying you must be taught TypeScript. Perhaps it is for that full-stack function, or maybe you are uninterested in explaining why Python is “completely tremendous” for giant codebases.

This is the factor: TypeScript is not simply “JavaScript with sorts.” It is what JavaScript ought to have been from the beginning. And when you’re coming from Python, you already perceive greater than you suppose.

 

Going from Python to TypeScript

 
Python offers you duck typing and dynamic flexibility. TypeScript offers you a similar flexibility with a security internet. Consider it as Python’s mypy if mypy really labored in every single place.

In Python, you may name any technique on any object and “hope” it really works. TypeScript tells you at compile time whether or not it can work, saving you from these "AttributeError: 'NoneType' object has no attribute 'identify'" moments.

# Python: You hope this works
def process_user(person):
    return person.identify.higher()

// TypeScript: You already know this works
perform processUser(person: Person): string {
    return person.identify.toUpperCase();
}

 

If person does not have a identify property, TypeScript catches it earlier than your code ever runs. So you do not want defensive if hasattr(obj, 'attribute') checks in every single place.

 

TypeScript Fundamentals

 
Let’s begin with the fundamentals of TypeScript.

 

// Variables and Primary Sorts

Python’s sort hints are elective options. TypeScript’s sorts are extra like enforced contracts. The excellent news? TypeScript can infer most sorts robotically, so that you need not annotate every little thing.

# Python
identify = "Alice"
age = 30
is_active = True
scores = [95, 87, 92]
person = {"identify": "Bob", "age": 25}

// TypeScript
const identify = "Alice";          // string (inferred)
const age = 30;                // quantity (inferred)
const isActive = true;         // boolean (inferred)
const scores = [95, 87, 92];   // quantity[] (inferred)
const person = { identify: "Bob", age: 25 }; // object (inferred)

// Or be specific
const identify: string = "Alice";
const scores: quantity[] = [95, 87, 92];

 

You solely want specific annotations when the inference is not apparent or if you need to be additional clear about your intentions.

 

// Capabilities

Perform syntax maps nearly instantly, however TypeScript’s method to default parameters is cleaner than Python’s mutable default argument gotchas.

# Python
def greet(identify: str, excited: bool = False) -> str:
    suffix = "!" if excited else "."
    return f"Hiya, {identify}{suffix}"

// TypeScript
perform greet(identify: string, excited = false): string {
    const suffix = excited ? "!" : ".";
    return `Hiya, ${identify}${suffix}`;
}

// Or arrow perform (Python lambda equal)
const greet = (identify: string, excited = false): string => 
    `Hiya, ${identify}${excited ? "!" : "."}`;

 

The arrow perform syntax is much like Python’s lambda, however extra highly effective. You possibly can write full perform our bodies or concise one-liners. Template literals (these backticks) work identical to Python’s f-strings.

 

// Courses

TypeScript lessons really feel extra streamlined than Python lessons. No extra self in every single place, and constructor parameters can robotically change into properties.

# Python
class Person:
    def __init__(self, identify: str, electronic mail: str):
        self.identify = identify
        self.electronic mail = electronic mail
    
    def greet(self) -> str:
        return f"Hello, I am {self.identify}"

// TypeScript
class Person {
    constructor(public identify: string, public electronic mail: string) {}
    
    greet(): string {
        return `Hello, I am ${this.identify}`;
    }
}

 

That public key phrase within the constructor is TypeScript’s shorthand for “create this property robotically and assign the parameter worth to it.” So that you don’t have to make use of the self.identify = identify boilerplate. It’s also possible to use personal or protected for encapsulation.

 

The place TypeScript Will get Fascinating

 
That is the place TypeScript begins to really feel fascinating as you progress past the fundamentals.

 

// Union Sorts (Python’s Union however higher)

Python’s Union sorts from the typing module work, however they’re generally verbose. TypeScript’s union sorts are constructed into the language.

# Python
from typing import Union
def process_id(user_id: Union[str, int]) -> str:
    return str(user_id)

// TypeScript
perform processId(userId: string | quantity): string {
    return userId.toString();
}

 

The | syntax is cleaner than Union[str, int], and TypeScript’s compiler can carry out extra subtle sort checking. It is aware of which strategies can be found primarily based on the precise sort at runtime.

 

// Literal Sorts

Python’s Literal sorts are comparatively new however useful. TypeScript, nevertheless, has rather more efficient literal sorts.

# Python
from typing import Literal
Standing = Literal["pending", "approved", "rejected"]

def update_status(standing: Standing) -> None:
    print(f"Standing: {standing}")

// TypeScript
sort Standing = "pending" | "permitted" | "rejected";

perform updateStatus(standing: Standing): void {
    console.log(`Standing: ${standing}`);
}

 

Attempt to move an invalid string like “perhaps” to updateStatus, and TypeScript will refuse to compile. Your editor will even present autocomplete for the legitimate choices. It is like having an enum that is really helpful.

 

// Interfaces

Python’s dataclasses are nice for creating structured knowledge:

# Python
from dataclasses import dataclass

@dataclass
class Person:
    identify: str
    electronic mail: str
    age: int

 

However interfaces in TypeScript are extra versatile. They describe the information with out creating a particular class implementation.

// TypeScript
interface Person {
    identify: string;
    electronic mail: string;
    age: quantity;
}

// Use it wherever
const person: Person = { identify: "Alice", electronic mail: "alice@instance.com", age: 30 };

 

Any object that has the fitting properties robotically satisfies the interface. No inheritance required, no specific class instantiation wanted. It is duck typing with compile-time verification.

 

Studying Extra TypeScript Options

 
Now let’s be taught a couple of extra helpful options of TypeScript.

 

// Generics (Like Python’s TypeVar)

Python’s generic typing works, however it’s clunky. TypeScript generics really feel pure and highly effective proper out of the field.

# Python
from typing import TypeVar, Listing
T = TypeVar('T')

def first(gadgets: Listing[T]) -> T:
    return gadgets[0]

// TypeScript
perform first(gadgets: T[]): T {
    return gadgets[0];
}

// Works with something
const firstNumber = first([1, 2, 3]);      // quantity
const firstString = first(["a", "b", "c"]);  // string

 

TypeScript robotically infers the generic sort from utilization. Name first with numbers, and it returns a quantity. Name it with strings, and it returns a string. No specific sort parameters wanted, however you may present them when the inference is not clear.

 

// Kind Guards

Kind guards allow you to write runtime checks that the compiler understands and makes use of to slender sorts in subsequent code.

perform isString(worth: unknown): worth is string {
    return typeof worth === "string";
}

perform processValue(worth: string | quantity) {
    if (isString(worth)) {
        return worth.toUpperCase();
    }
    return worth.toFixed(2);
}

 

The worth is string syntax tells TypeScript that if this perform returns true, the parameter is certainly a string. Contained in the if block, you get full string strategies and properties. No casting, no assertions, simply sensible sort narrowing primarily based in your runtime checks.

 

// Mapped Sorts (Listing Comprehensions for Sorts)

Consider mapped sorts as record comprehensions, however for sort transformations. They allow you to create new sorts by reworking current ones.

sort Person = {
    identify: string;
    electronic mail: string;
    age: quantity;
};

// Make all properties elective
sort PartialUser = Partial;

// Make all properties readonly
sort ReadonlyUser = Readonly;

// Choose particular properties
sort UserContact = Choose;

 

These utility sorts ship with TypeScript and clear up widespread patterns. For those who want a sort that is like Person however with elective fields for updates, you need to use Partial. And if it’s good to guarantee no modifications after creation, use Readonly.

 

Error Dealing with in TypeScript

 
Python builders love attempt/besides blocks, however they’ll get verbose. TypeScript makes use of a special method utilizing end result sorts and union sorts for error dealing with that make errors specific in your perform signatures:

// Outcome sort sample (impressed by Rust)
sort Outcome = { success: true; knowledge: T } | { success: false; error: E };

// Make this file a module
export {};

// Assuming you've a Person sort and parseUser perform
interface Person {
    identify: string;
    // ... different properties
}

perform parseUser(knowledge: unknown): Person {
    // Your parsing logic right here
    // This could throw an error if parsing fails
    if (!knowledge || typeof knowledge !== 'object') {
        throw new Error('Invalid person knowledge');
    }
    
    const person = knowledge as any;
    if (!person.identify || typeof person.identify !== 'string') {
        throw new Error('Person identify is required and have to be a string');
    }
    
    return { identify: person.identify };
}

async perform safeParseUser(knowledge: unknown): Promise> {
    attempt {
        const person = parseUser(knowledge);
        return { success: true, knowledge: person };
    } catch (error) {
        // Repair: Deal with the case the place error won't have a message property
        const errorMessage = error instanceof Error ? error.message : String(error);
        return { success: false, error: errorMessage };
    }
}

 

You need to use it like so:

// Utilization (wrapped in an async perform or use at high degree in a module)
async perform instance() {
    const rawData = { identify: "John Doe" }; // Instance knowledge
    const end result = await safeParseUser(rawData);

    if (end result.success) {
        console.log(end result.knowledge.identify); // TypeScript is aware of that is Person
    } else {
        console.error(end result.error);   // TypeScript is aware of that is string
    }
}

// Name the instance perform
instance();

 

This sample makes errors specific within the sort system. As a substitute of exceptions flying round invisibly, errors change into a part of the return sort. The Outcome sort forces you to deal with each success and failure circumstances. TypeScript’s discriminated unions make this sample easy: the success property tells which department of the union you are in, so it is aware of whether or not knowledge or error is obtainable.

 

Conclusion

 
TypeScript is changing into tremendous well-liked in net improvement, large-scale functions, and wherever you want strong APIs.

The transition is not about studying a brand new language. It is extra about making use of every little thing you recognize about good software program design in a special ecosystem. Your Python instinct for clear code, readable APIs, and considerate abstractions interprets instantly.

So open VS Code, create a .ts file, and begin coding. The worst factor that occurs? You be taught one thing new. One of the best factor? You may simply discover your new favourite language. Glad coding!
 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, knowledge science, and content material creation. Her areas of curiosity and experience embrace DevOps, knowledge science, and pure language processing. She enjoys studying, writing, coding, and low! Presently, she’s engaged on studying and sharing her data with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments