TypeScript
TypeScript-kärntyper
Sök…
Syntax
- låt variabelName: VariableType;
- function functionName (parameterName: VariableType, parameterWithDefault: VariableType = ParameterDefault, optionalParameter ?: VariableType, ... variardicParameter: VariableType []): ReturnType {/*...*/};
Boolean
En boolean representerar den mest grundläggande datatypen i TypeScript, i syfte att tilldela sanna / falska värden.
// 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;
siffra
Liksom JavaScript är siffrorna flytande punktvärden.
let pi: number = 3.14; // base 10 decimal by default
let hexadecimal: number = 0xFF; // 255 in decimal
ECMAScript 2015 tillåter binär och oktal.
let binary: number = 0b10; // 2 in decimal
let octal: number = 0o755; // 493 in decimal
Sträng
Textdata:
let singleQuotes: string = 'single';
let doubleQuotes: string = "double";
let templateString: string = `I am ${ singleQuotes }`; // I am single
Array
En mängd värden:
let threePigs: number[] = [1, 2, 3];
let genericStringArray: Array<string> = ['first', '2nd', '3rd'];
Enum
En typ för att namnge en uppsättning numeriska värden:
Antalvärden som standard är 0:
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
let bestDay: Day = Day.Saturday;
Ställ in ett startnummer:
enum TenPlus { Ten = 10, Eleven, Twelve }
eller tilldela värden:
enum MyOddSet { Three = 3, Five = 5, Seven = 7, Nine = 9 }
Några
Om du är osäker på en typ finns any
tillgänglig:
let anything: any = 'I am a string';
anything = 5; // but now I am the number 5
Tomhet
Om du inte har någon typ alls, används ofta för funktioner som inte returnerar någonting:
function log(): void {
console.log('I return nothing');
}
void
Kan endast tilldelas null
eller undefined
.
tupel
Arraytyp med kända och eventuellt olika typer:
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'
Skriv in funktionsargument och returvärde. siffra
När du skapar en funktion i TypeScript kan du ange datatypen för funktionens argument och datatypen för returvärdet
Exempel:
function sum(x: number, y: number): number {
return x + y;
}
Här betyder syntaxen x: number, y: number
att funktionen kan acceptera två argument x
och y
och de kan bara vara siffror och (...): number {
betyder att returvärdet bara kan vara ett nummer
Användande:
sum(84 + 76) // will be return 160
Notera:
Du kan inte göra det
function sum(x: string, y: string): number {
return x + y;
}
eller
function sum(x: number, y: number): string {
return x + y;
}
det kommer att få följande fel:
error TS2322: Type 'string' is not assignable to type 'number'
och error TS2322: Type 'number' is not assignable to type 'string'
Skriv in funktionsargument och returvärde. Sträng
Exempel:
function hello(name: string): string {
return `Hello ${name}!`;
}
Här syntaxen name: string
innebär att funktionen kan acceptera ett name
argument och detta argument kan endast sträng och (...): string {
innebär att returvärdet kan endast vara en sträng
Användande:
hello('StackOverflow Documentation') // will be return Hello StackOverflow Documentation!
Sträng bokstavliga typer
Sträng bokstavliga typer låter dig ange det exakta värdet en sträng kan ha.
let myFavoritePet: "dog";
myFavoritePet = "dog";
Alla andra strängar ger ett fel.
// Error: Type '"rock"' is not assignable to type '"dog"'.
// myFavoritePet = "rock";
Tillsammans med Type Aliases och Union Types får du ett enumliknande beteende.
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 Types kan användas för att skilja överbelastningar.
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)
De fungerar bra för användardefinierade typskydd.
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();
}
}
Fullständig exempelkod
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.
Korsningstyper
En skärningstyp kombinerar elementet av två eller flera typer.
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
En const Enum är densamma som en normal Enum. Förutom att inget objekt genereras vid sammanställningstiden. Istället ersätts de bokstavliga värdena där const Enum används.
// 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]);
Som jämförelse, en normal 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"