Skip to main content

Syntax

This page will provide information on TypeScript syntax.

tip

Check out the official TypeScript docs for more information: https://www.typescriptlang.org/docs/

Defining Properties

The syntax for defining properties is as follows:

AccessModifier PropertyName : TypeName;

Serialization

In TypeScript, you can define properties so they are serialized in Unity. Any Unity serializable type as well as any custom TypeScript class with Unity serializable properties is also valid. Here are some notable examples:

public myNumber : number;

//You can serialize multi-dimensional arrays
public myArray : int[][][];

//You can serialize generics without creating a concrete class
public myGeneric : CustomGenericType<int>;

//You can serialize generic C# types
public myList : List$1<int>;

Decorators

Decorators are the TypeScript equivalence of C# attributes. They are used for properties to control how they’re serialized and rendered in the Inspector. Here are the following supported decorators:

  • @SerializeField → Marks a private property as serialized
  • @NonSerialized → Marks a public property as non serialized
  • @HideInInspector → Serializes the public field but hides in Inspector
  • @Header → Adds a header on top of the property, use to group properties
  • @Space → Adds a space before a property in the Inspector
  • @Tooltip → Adds a tooltip for the property when you hover over it in the Inspector

Here are some examples showcasing decorators:

@Header("Player Settings")
@HideInInspector public playerName: string;
@NonSerialized public playerID: string;
@Space()
@Tooltip("How many seconds the player should rotate")
@SerializeField private rotationDuration: number = 2;

Importing Packages

Importing packages is required in TypeScript for accessing UnityEngine API, Genies SDK, and classes from other scripts. The syntax for importing packages is as follows:

import { PackageName } from 'LibraryName'

Here are some notable examples importing packages:

//Importing one package from a library
import { GeniesSdk } from 'Genies.Components.SDK.Core';

//Importing multiple packages from one library
import { MonoBehaviour, GameObject, Vector3 } from 'UnityEngine'

//Importing all packages from a library
import * as DGT from 'DG.Tweening';

//Importing a class from another TypeScript file
import SomeOtherClass from './SomeOtherClass'

Writing Methods

The syntax for writing methods is as follows:

AccessModifier MethodName(Parameters): ReturnType {}

Method Overloading

C# allows method overloading by defining multiple methods with the same name but different parameter lists. TypeScript does not support traditional method overloading; instead, you can achieve similar behavior using default parameter values or union types.

Generators

TypeScript supports generators using the function* syntax and yield keyword, allowing lazy evaluation of sequences. C# can achieve similar behavior using iterator (IEnumerable) methods and the yield keyword.

Examples

Here are some notable examples writing methods:

// Method with no parameters and void return type
public TypeScriptMethod(): void {
console.log("TypeScript Method with no parameters and void return type");
}

// Method with parameters and return type
public TypeScriptMethod(x: number, y: number): number {
return x + y;
}

// Method with optional parameters
public TypeScriptMethodWithOptionalParams(x: number, y?: number): void {
console.log(`TypeScript Method with optional parameter: ${x + (y || 0)}`);
}

// Method with explicit return type position
public TypeScriptMethodWithReturnTypePosition(x: number, y: number): number {
const sum: number = x + y;
return sum;
}

// Method Overriding in TypeScript
public override TypeScriptMethod(): void {
console.log("TypeScript Method Overridden");
}

// Generators in TypeScript
public *generator(): Iterable<number> {
yield 1;
yield 2;
yield 3;
}

Writing Classes

Classes in TypeScript are similar to classes in C#. You can inherit a class by using the extend keyword. In order for another script to import your class, the class must use the keyword export or default. Here is an example writing classes:

export class MyClass {
private myProperty: string;

constructor(myProperty: string) {
this.myProperty = myProperty;
}

myMethod() {
console.log(`My property value is ${this.myProperty}`);
}
}

export class InheritedClass extends MyClass {
}

Writing Interfaces

Interfaces in TypeScript are also similar in C#. You can inherit an interface by using the implements keyword. Here is an example writing interfaces:

interface Shape {
area(): number;
}

class Circle implements Shape {
constructor(private radius: number) {}

area() {
return Math.PI * this.radius ** 2;
}
}

Collections

When using TypeScript, you should stick to using the native collections and only use the C# collections when interacting with the C# APIs.

Arrays

const numbers: number[] = [1, 2, 3, 4, 5];
const strings: string[] = ['a', 'b', 'c'];

Tuples

Tuples are arrays with fixed-length and fixed types.

const tuple: [number, string] = [1, 'a'];

Objects

Objects are key-value pairs.

const person: { name: string, age: number } = { name: 'John', age: 30 };

Maps

Maps are collections of key-value pairs with keys of any type.

const map = new Map<number, string>();
map.set(1, 'One');
map.set(2, 'Two');

Sets

Sets are collections of unique values.

const set = new Set<number>();
set.add(1);
set.add(2);
set.add(3);

Queues

Queues are collections with FIFO (First In, First Out).

const queue: number[] = [];
queue.push(1);
queue.push(2);
queue.push(3);
const dequeuedItem = queue.shift(); // Removes and returns the first item

Stacks

Stacks are collections with LIFO (Last In, First Out).

const stack: number[] = [];
stack.push(1);
stack.push(2);
stack.push(3);
const poppedItem = stack.pop(); // Removes and returns the last item

Loops

For Loop

for (let i = 0; i < 5; i++) {
console.log(i);
}

For Of Loop

The for...of loop is used for iterating over arrays, strings, maps, sets, and other similar iterables.

const array = [1, 2, 3, 4, 5];
for (const item of array) {
console.log(item);
}

const set = new Set<number>();
set.add(1);
set.add(2);
set.add(3);
for (const item of set.values()) {
console.log(item);
}

For In Loop

The for...in loop is used for iterating over object keys.

const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + ': ' + obj[key]);
}
}

While Loop

let count = 0;
while (count < 5) {
console.log(count);
count++;
}

Do While Loop

let num = 0;
do {
console.log(num);
num++;
} while (num < 5);

Using JSON

TypeScript has built-in functions to parse and stringify JSON-formatted data. Here is an example of utilizing JSON:

import { MonoBehaviour } from 'UnityEngine';

export default class MyScript extends MonoBehaviour {

Start() {
let jsonData = '{"id":"USER1234", "name":"genies", "age":15}';

// Converting a JSON string to an object
let userObject : User = JSON.parse(jsonData);
console.log(userObject.id);
console.log(userObject.name);
console.log(userObject.age);

userObject.age = 16;

// Converting an object to a JSON string
let newJsonData = JSON.stringify(userObject);
console.log(newJsonData);
}
}

class User {
constructor(public id: string, public name: string, public age: number) {}
}