SomonScriptDocsType system
Chapter 10 • Type system

Type system in SomonScript

A type system helps you find errors before the program even runs and write more reliable code.

1. Union types

Sometimes a variable can have more than one type, for example be either a number or a string. Union types are used for this.

A union type for a result

A variable that can hold either a number or a string.

example.som
навъ НатиҷаЁХато = рақам | сатр;

функсия ҳисоб(а: рақам, б: рақам): НатиҷаЁХато {
  агар (б === 0) {
    бозгашт "Хато: тақсим ба сифр";
  }
  бозгашт а / б;
}

тағ натиҷа: НатиҷаЁХато = ҳисоб(10, 2);
чоп.сабт("Натиҷа: " + натиҷа);
terminal
somon run types-union.som
Натиҷа: 5

2. Composite types for objects

An object type can be described separately so that several variables and functions can use it.

An object type for a student

Using a type to describe the structure of an object.

example.som
навъ Донишҷӯ = {
  ном: сатр;
  синну_сол: рақам;
  фаъол_аст: мантиқӣ;
};

функсия нишон_додани_донишҷӯ(д: Донишҷӯ): беджавоб {
  чоп.сабт("Донишҷӯ: " + д.ном + ", синну сол: " + д.синну_сол);
}

тағ ахмад: Донишҷӯ = {
  ном: "Аҳмад",
  синну_сол: 20,
  фаъол_аст: дуруст,
};

нишон_додани_донишҷӯ(ахмад);
terminal
somon run types-student-type.som
Донишҷӯ: Аҳмад, синну сол: 20

3. Exercises

These exercises will help reinforce the topic of the type system.

  1. Create a type where the result can be either a number or an error message, and write a function that uses this type.
  2. Create a type Китоб with properties for the title, author and number of pages, and use it to describe a list of books.
  3. Create a type for the result of a network request (success + data, or an error) and write an example function.