Data-Types

The capabilities of data-types in different languages.

C# Data Types

TypeScript Data-Types


Primitive Types

Basic data types provided by the language (e.g., integers, floats, strings).

C# provides built-in primitive types such as int, double, bool, and string.

using System; class Program { static void Main(string[] args) { int number = 42; double pi = 3.14; bool isTrue = true; string text = "Hello, C#"; Console.WriteLine(number); Console.WriteLine(pi); Console.WriteLine(isTrue); Console.WriteLine(text); } }

Structured Data Type Definitions (Interfaces, Types)

TypeScript allows defining structured data with interface or type. Fields can be optional (?).

interface User { id: number; name: string; email?: string; // Optional field } const user: User = { id: 1, name: "Alice" };

Alternatively, using type:

type Product = { id: number; name: string; price: number; category?: string; // Optional field }; const item: Product = { id: 101, name: "Laptop", price: 1200 };

Structured Data Type Definitions

Definitions for structured data types like Dataclasses, Dictionaries, or TypedDict.

C# supports structured data types like dictionaries and custom classes.

using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var dictionary = new Dictionary<string, int> { { "One", 1 }, { "Two", 2 } }; foreach (var kvp in dictionary) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } }

Classes

class Person { name: string; constructor(name: string) { this.name = name; console.log(`${this.name} is created`); } greet(): void { console.log(`Hello, my name is ${this.name}`); } // No direct destructor, but `finalize` can be used in specific environments } const person = new Person("Alice"); person.greet(); // Output: // Alice is created // Hello, my name is Alice

Typescript does not have destructors.


Classes

Blueprints for creating objects with attributes and methods.

C# allows defining classes with properties and methods.

using System; class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { Person person = new Person { Name = "Alice", Age = 30 }; Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } }

Class Property Accessors

class Person { private _name: string; private _age: number; constructor(name: string, age: number) { this._name = name; this._age = age; } // Getter for name get name(): string { return this._name; } // Setter for name set name(newName: string) { if (newName.length < 3) { throw new Error("Name must be at least 3 characters long."); } this._name = newName; } } // Usage const person = new Person("Alice", 25); console.log(person.name); // Getter: Alice person.name = "Bob"; // Setter console.log(person.name); // Getter: Bob

Class Property Accessors

Methods to get or set class properties.

C# supports property accessors for encapsulating fields.

using System; class Person { private string name; public string Name { get { return name; } set { name = value; } } } class Program { static void Main(string[] args) { Person person = new Person { Name = "Alice" }; Console.WriteLine(person.Name); } }

Class Generics

class Box<T> { private content: T; constructor(content: T) { this.content = content; } getContent(): T { return this.content; } } const intBox = new Box<number>(10); console.log(intBox.getContent()); // 10 const strBox = new Box<string>("TypeScript"); console.log(strBox.getContent()); // "TypeScript"

Class Generics

Support for generic programming with classes.

C# supports generic classes for type-safe data structures.

using System; class Box<T> { public T Value { get; set; } } class Program { static void Main(string[] args) { Box<int> box = new Box<int> { Value = 42 }; Console.WriteLine(box.Value); } }

Class Inheritance

class Animal { name: string; constructor(name: string) { this.name = name; } makeSound(): void { console.log("Some generic animal sound"); } } class Dog extends Animal { constructor(name: string) { super(name); // Calls parent constructor } makeSound(): void { console.log("Woof!"); } } const dog = new Dog("Buddy"); dog.makeSound(); // "Woof!"

Classes can also implement interface (pure abstract class):

interface Speakable { speak(): void; } class Robot implements Speakable { speak(): void { console.log("Beep boop!"); } } const bot = new Robot(); bot.speak(); // "Beep boop!"

Abstract classes also supported, with a parial implementation:

abstract class Vehicle { abstract move(): void; // Must be implemented by subclass stop(): void { console.log("Stopping..."); } } class Car extends Vehicle { move(): void { console.log("Driving..."); } } const car = new Car(); car.move(); // "Driving..." car.stop(); // "Stopping..."

Class Inheritance

Mechanism to create a new class from an existing class.

C# supports inheritance for creating hierarchies of classes.

using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Woof!"); } } class Program { static void Main(string[] args) { Animal animal = new Dog(); animal.Speak(); } }

Enum Definitions

Enums define a set of named constants.

enum Status { Pending, InProgress, Completed, } const currentStatus: Status = Status.InProgress;
  • Enum values default to numeric (starting from 0).
  • Custom values can be assigned:
enum Role { User = "USER", Admin = "ADMIN", } const userRole: Role = Role.Admin;

Enum Definitions

Define a set of named constants.

C# supports enums for defining named constants.

using System; enum Color { Red, Green, Blue } class Program { static void Main(string[] args) { Color color = Color.Red; Console.WriteLine(color); } }

Type Casting in TypeScript

TypeScript provides mechanisms for type casting to convert between types or assert the type of a value. This is useful when working with dynamic data or narrowing types.

Explicit Type Casting. TypeScript allows explicit type casting using the as keyword or angle-bracket syntax (<>).

let value: unknown = "Hello, TypeScript"; // Casting to a string let strLength: number = (value as string).length; console.log(strLength); // Output: 17 // Alternatively, using angle-bracket syntax let strLengthAlt: number = (<string>value).length; console.log(strLengthAlt); // Output: 17
  • Use as for readability and compatibility with JSX.
  • Type casting does not perform runtime type checks; it only tells the compiler to treat the value as a specific type.

Type guards are used to narrow down the type of a variable within a block of code. They are often used with typeof, instanceof, or custom type-checking functions.

function processValue(value: string | number): void { if (typeof value === "string") { console.log(`String value: ${value.toUpperCase()}`); } else { console.log(`Number value: ${value * 2}`); } } processValue("hello"); // Output: String value: HELLO processValue(42); // Output: Number value: 84
class Animal { makeSound(): void { console.log("Some generic animal sound"); } } class Dog extends Animal { makeSound(): void { console.log("Woof!"); } } function identifyAnimal(animal: Animal): void { if (animal instanceof Dog) { console.log("This is a dog"); } else { console.log("This is some other animal"); } } const dog = new Dog(); identifyAnimal(dog); // Output: This is a dog

Type assertions are used to tell the TypeScript compiler to treat a value as a specific type. This is useful when you know more about the type than the compiler does.

let someValue: unknown = "TypeScript"; // Assert that the value is a string let strLength: number = (someValue as string).length; console.log(strLength); // Output: 10

You can combine type assertions or type guards with conditional statements to handle dynamic types.

function printValue(value: string | number): void { if (typeof value === "string") { console.log(`String: ${value}`); } else { console.log(`Number: ${value}`); } } printValue("Hello"); // Output: String: Hello printValue(123); // Output: Number: 123

You can define custom type guard functions to narrow down types.

interface Cat { meow(): void; } interface Dog { bark(): void; } function isCat(animal: Cat | Dog): animal is Cat { return (animal as Cat).meow !== undefined; } function handleAnimal(animal: Cat | Dog): void { if (isCat(animal)) { animal.meow(); } else { animal.bark(); } } const cat: Cat = { meow: () => console.log("Meow!") }; const dog: Dog = { bark: () => console.log("Woof!") }; handleAnimal(cat); // Output: Meow! handleAnimal(dog); // Output: Woof!

Type Casting

Convert a value from one type to another.

C# supports explicit and implicit type casting.

using System; class Program { static void Main(string[] args) { int number = 42; double pi = number; // Implicit casting int truncated = (int)pi; // Explicit casting Console.WriteLine(pi); Console.WriteLine(truncated); } }

Missing


??

Missing