TypeScript
TypeScript-Kerntypen
Suche…
Syntax
- let variableName: Variablentyp;
- function functionName (parameterName: Variablentyp, parameterWithDefault: Variablentyp = ParameterDefault, optionalParameter ?: Variablentyp, ... variardicParameter: Variablentyp []): ReturnType {/*...*/};
Boolean
Ein Boolescher Wert stellt den grundlegendsten Datentyp in TypeScript dar, um True / False-Werte zuzuweisen.
// set with initial value (either true or false)
let isTrue: boolean = true;
// defaults to 'undefined', when not explicitely set
let unsetBool: boolean;
// can also be set to 'null' as well
let nullableBool: boolean = null;
Nummer
Wie bei JavaScript sind Zahlen Gleitkommawerte.
let pi: number = 3.14; // base 10 decimal by default
let hexadecimal: number = 0xFF; // 255 in decimal
ECMAScript 2015 erlaubt binär und oktal.
let binary: number = 0b10; // 2 in decimal
let octal: number = 0o755; // 493 in decimal
String
Textdatentyp:
let singleQuotes: string = 'single';
let doubleQuotes: string = "double";
let templateString: string = `I am ${ singleQuotes }`; // I am single
Array
Ein Array von Werten:
let threePigs: number[] = [1, 2, 3];
let genericStringArray: Array<string> = ['first', '2nd', '3rd'];
Enum
Ein Typ, um einen Satz numerischer Werte zu benennen:
Zahlenwerte standardmäßig auf 0:
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
let bestDay: Day = Day.Saturday;
Legen Sie eine Standardstartnummer fest:
enum TenPlus { Ten = 10, Eleven, Twelve }
oder Werte zuweisen:
enum MyOddSet { Three = 3, Five = 5, Seven = 7, Nine = 9 }
Irgendein
Wenn Sie sich bezüglich eines Typs any
sicher sind, ist any
verfügbar:
let anything: any = 'I am a string';
anything = 5; // but now I am the number 5
Leere
Wenn Sie überhaupt keinen Typ haben, wird er normalerweise für Funktionen verwendet, die nichts zurückgeben:
function log(): void {
console.log('I return nothing');
}
void
types Kann nur null
oder undefined
.
Tupel
Array-Typ mit bekannten und möglicherweise unterschiedlichen Typen:
let day: [number, string];
day = [0, 'Monday']; // valid
day = ['zero', 'Monday']; // invalid: 'zero' is not numeric
console.log(day[0]); // 0
console.log(day[1]); // Monday
day[2] = 'Saturday'; // valid: [0, 'Saturday']
day[3] = false; // invalid: must be union type of 'number | string'
Typen in Funktionsargumente und Rückgabewert. Nummer
Beim Erstellen einer Funktion in TypeScript können Sie den Datentyp der Funktionsargumente und den Datentyp für den Rückgabewert angeben
Beispiel:
function sum(x: number, y: number): number {
return x + y;
}
Hier bedeutet die Syntax x: number, y: number
, dass die Funktion zwei Argumente x
und y
annehmen kann und diese nur aus Zahlen und (...): number {
kann, bedeutet, dass der Rückgabewert nur eine Zahl sein kann
Verwendungszweck:
sum(84 + 76) // will be return 160
Hinweis:
Das kannst du nicht tun
function sum(x: string, y: string): number {
return x + y;
}
oder
function sum(x: number, y: number): string {
return x + y;
}
Es werden folgende Fehler angezeigt:
error TS2322: Type 'string' is not assignable to type 'number'
und der error TS2322: Type 'number' is not assignable to type 'string'
werden
Typen in Funktionsargumente und Rückgabewert. String
Beispiel:
function hello(name: string): string {
return `Hello ${name}!`;
}
Hier ist die Syntax name: string
bedeutet , dass die Funktion eines annehmen name
Argument und dieses Argument kann nur String sein und (...): string {
bedeutet , dass der Rückgabewert nur eine Zeichenfolge sein kann
Verwendungszweck:
hello('StackOverflow Documentation') // will be return Hello StackOverflow Documentation!
String-Literal-Typen
Mit String-Literal-Typen können Sie den genauen Wert angeben, den eine Zeichenfolge haben kann.
let myFavoritePet: "dog";
myFavoritePet = "dog";
Jede andere Zeichenfolge gibt einen Fehler aus.
// Error: Type '"rock"' is not assignable to type '"dog"'.
// myFavoritePet = "rock";
Zusammen mit Typenaliasen und Union-Typen erhalten Sie ein enumeartiges Verhalten.
type Species = "cat" | "dog" | "bird";
function buyPet(pet: Species, name: string) : Pet { /*...*/ }
buyPet(myFavoritePet /* "dog" as defined above */, "Rocky");
// Error: Argument of type '"rock"' is not assignable to parameter of type "'cat' | "dog" | "bird". Type '"rock"' is not assignable to type '"bird"'.
// buyPet("rock", "Rocky");
String-Literal-Typen können verwendet werden, um Überladungen zu unterscheiden.
function buyPet(pet: Species, name: string) : Pet;
function buyPet(pet: "cat", name: string): Cat;
function buyPet(pet: "dog", name: string): Dog;
function buyPet(pet: "bird", name: string): Bird;
function buyPet(pet: Species, name: string) : Pet { /*...*/ }
let dog = buyPet(myFavoritePet /* "dog" as defined above */, "Rocky");
// dog is from type Dog (dog: Dog)
Sie funktionieren gut für benutzerdefinierte Typenschutz.
interface Pet {
species: Species;
eat();
sleep();
}
interface Cat extends Pet {
species: "cat";
}
interface Bird extends Pet {
species: "bird";
sing();
}
function petIsCat(pet: Pet): pet is Cat {
return pet.species === "cat";
}
function petIsBird(pet: Pet): pet is Bird {
return pet.species === "bird";
}
function playWithPet(pet: Pet){
if(petIsCat(pet)) {
// pet is now from type Cat (pet: Cat)
pet.eat();
pet.sleep();
} else if(petIsBird(pet)) {
// pet is now from type Bird (pet: Bird)
pet.eat();
pet.sing();
pet.sleep();
}
}
Vollständiger Beispielcode
let myFavoritePet: "dog";
myFavoritePet = "dog";
// Error: Type '"rock"' is not assignable to type '"dog"'.
// myFavoritePet = "rock";
type Species = "cat" | "dog" | "bird";
interface Pet {
species: Species;
name: string;
eat();
walk();
sleep();
}
interface Cat extends Pet {
species: "cat";
}
interface Dog extends Pet {
species: "dog";
}
interface Bird extends Pet {
species: "bird";
sing();
}
// Error: Interface 'Rock' incorrectly extends interface 'Pet'. Types of property 'species' are incompatible. Type '"rock"' is not assignable to type '"cat" | "dog" | "bird"'. Type '"rock"' is not assignable to type '"bird"'.
// interface Rock extends Pet {
// type: "rock";
// }
function buyPet(pet: Species, name: string) : Pet;
function buyPet(pet: "cat", name: string): Cat;
function buyPet(pet: "dog", name: string): Dog;
function buyPet(pet: "bird", name: string): Bird;
function buyPet(pet: Species, name: string) : Pet {
if(pet === "cat") {
return {
species: "cat",
name: name,
eat: function () {
console.log(`${this.name} eats.`);
}, walk: function () {
console.log(`${this.name} walks.`);
}, sleep: function () {
console.log(`${this.name} sleeps.`);
}
} as Cat;
} else if(pet === "dog") {
return {
species: "dog",
name: name,
eat: function () {
console.log(`${this.name} eats.`);
}, walk: function () {
console.log(`${this.name} walks.`);
}, sleep: function () {
console.log(`${this.name} sleeps.`);
}
} as Dog;
} else if(pet === "bird") {
return {
species: "bird",
name: name,
eat: function () {
console.log(`${this.name} eats.`);
}, walk: function () {
console.log(`${this.name} walks.`);
}, sleep: function () {
console.log(`${this.name} sleeps.`);
}, sing: function () {
console.log(`${this.name} sings.`);
}
} as Bird;
} else {
throw `Sorry we don't have a ${pet}. Would you like to buy a dog?`;
}
}
function petIsCat(pet: Pet): pet is Cat {
return pet.species === "cat";
}
function petIsDog(pet: Pet): pet is Dog {
return pet.species === "dog";
}
function petIsBird(pet: Pet): pet is Bird {
return pet.species === "bird";
}
function playWithPet(pet: Pet) {
console.log(`Hey ${pet.name}, let's play.`);
if(petIsCat(pet)) {
// pet is now from type Cat (pet: Cat)
pet.eat();
pet.sleep();
// Error: Type '"bird"' is not assignable to type '"cat"'.
// pet.type = "bird";
// Error: Property 'sing' does not exist on type 'Cat'.
// pet.sing();
} else if(petIsDog(pet)) {
// pet is now from type Dog (pet: Dog)
pet.eat();
pet.walk();
pet.sleep();
} else if(petIsBird(pet)) {
// pet is now from type Bird (pet: Bird)
pet.eat();
pet.sing();
pet.sleep();
} else {
throw "An unknown pet. Did you buy a rock?";
}
}
let dog = buyPet(myFavoritePet /* "dog" as defined above */, "Rocky");
// dog is from type Dog (dog: Dog)
// Error: Argument of type '"rock"' is not assignable to parameter of type "'cat' | "dog" | "bird". Type '"rock"' is not assignable to type '"bird"'.
// buyPet("rock", "Rocky");
playWithPet(dog);
// Output: Hey Rocky, let's play.
// Rocky eats.
// Rocky walks.
// Rocky sleeps.
Schnittarten
Ein Schnittpunkttyp kombiniert das Mitglied von zwei oder mehr Typen.
interface Knife {
cut();
}
interface BottleOpener{
openBottle();
}
interface Screwdriver{
turnScrew();
}
type SwissArmyKnife = Knife & BottleOpener & Screwdriver;
function use(tool: SwissArmyKnife){
console.log("I can do anything!");
tool.cut();
tool.openBottle();
tool.turnScrew();
}
const Enum
Ein const-Enum ist dasselbe wie ein normales Enum. Nur wird zur Kompilierzeit kein Objekt generiert. Stattdessen werden die Literalwerte ersetzt, wenn das const Enum verwendet wird.
// Typescript: A const Enum can be defined like a normal Enum (with start value, specifig values, etc.)
const enum NinjaActivity {
Espionage,
Sabotage,
Assassination
}
// Javascript: But nothing is generated
// Typescript: Except if you use it
let myFavoriteNinjaActivity = NinjaActivity.Espionage;
console.log(myFavoritePirateActivity); // 0
// Javascript: Then only the number of the value is compiled into the code
// var myFavoriteNinjaActivity = 0 /* Espionage */;
// console.log(myFavoritePirateActivity); // 0
// Typescript: The same for the other constant example
console.log(NinjaActivity["Sabotage"]); // 1
// Javascript: Just the number and in a comment the name of the value
// console.log(1 /* "Sabotage" */); // 1
// Typescript: But without the object none runtime access is possible
// Error: A const enum member can only be accessed using a string literal.
// console.log(NinjaActivity[myFavoriteNinjaActivity]);
Zum Vergleich ein normales Enum
// Typescript: A normal Enum
enum PirateActivity {
Boarding,
Drinking,
Fencing
}
// Javascript: The Enum after the compiling
// var PirateActivity;
// (function (PirateActivity) {
// PirateActivity[PirateActivity["Boarding"] = 0] = "Boarding";
// PirateActivity[PirateActivity["Drinking"] = 1] = "Drinking";
// PirateActivity[PirateActivity["Fencing"] = 2] = "Fencing";
// })(PirateActivity || (PirateActivity = {}));
// Typescript: A normale use of this Enum
let myFavoritePirateActivity = PirateActivity.Boarding;
console.log(myFavoritePirateActivity); // 0
// Javascript: Looks quite similar in Javascript
// var myFavoritePirateActivity = PirateActivity.Boarding;
// console.log(myFavoritePirateActivity); // 0
// Typescript: And some other normale use
console.log(PirateActivity["Drinking"]); // 1
// Javascript: Looks quite similar in Javascript
// console.log(PirateActivity["Drinking"]); // 1
// Typescript: At runtime, you can access an normal enum
console.log(PirateActivity[myFavoritePirateActivity]); // "Boarding"
// Javascript: And it will be resolved at runtime
// console.log(PirateActivity[myFavoritePirateActivity]); // "Boarding"