Buscar..


Sintaxis

  • deja variableName: VariableType;
  • función nombre de función (nombre_parámetro: TipoDeVariable, parámetroDeArteDefault: TipoDeVariable = Parámetro Predeterminado, opcional ¿Parámetro ?: Tipo De Variable, ... variarParámetro: VariableType []): ReturnType {/*...*/};

Booleano

Un booleano representa el tipo de datos más básico en TypeScript, con el propósito de asignar valores de verdadero / falso.

// 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;

Número

Al igual que JavaScript, los números son valores de punto flotante.

let pi: number = 3.14;           // base 10 decimal by default
let hexadecimal: number = 0xFF;  // 255 in decimal

ECMAScript 2015 permite binario y octal.

let binary: number = 0b10;   // 2 in decimal
let octal: number = 0o755;   // 493 in decimal

Cuerda

Tipo de datos textuales:

let singleQuotes: string = 'single';
let doubleQuotes: string = "double";
let templateString: string = `I am ${ singleQuotes }`; // I am single

Formación

Una matriz de valores:

let threePigs: number[] = [1, 2, 3];
let genericStringArray: Array<string> = ['first', '2nd', '3rd'];

Enumerar

Un tipo para nombrar un conjunto de valores numéricos:

Los valores numéricos por defecto son 0:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
let bestDay: Day = Day.Saturday;

Establecer un número inicial predeterminado:

enum TenPlus { Ten = 10, Eleven, Twelve }

o asignar valores:

enum MyOddSet { Three = 3, Five = 5, Seven = 7, Nine = 9 } 

Alguna

Cuando no esté seguro de un tipo, any está disponible:

let anything: any = 'I am a string';
anything = 5; // but now I am the number 5

Vacío

Si no tiene ningún tipo, se usa comúnmente para funciones que no devuelven nada:

function log(): void {
    console.log('I return nothing');
}

Tipos de void Solo se pueden asignar null o undefined .

Tupla

Tipo de matriz con tipos conocidos y posiblemente diferentes:

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'

Tipos en argumentos de función y valor de retorno. Número

Cuando crea una función en TypeScript, puede especificar el tipo de datos de los argumentos de la función y el tipo de datos para el valor de retorno

Ejemplo:

function sum(x: number, y: number): number {
    return x + y;
}

Aquí, la sintaxis x: number, y: number significa que la función puede aceptar dos argumentos x e y y solo pueden ser números y (...): number { significa que el valor de retorno solo puede ser un número

Uso:

sum(84 + 76) // will be return 160

Nota:

No puedes hacerlo

function sum(x: string, y: string): number {
    return x + y;
}

o

function sum(x: number, y: number): string {
    return x + y;
}

Recibirá los siguientes errores:

error TS2322: Type 'string' is not assignable to type 'number' y error TS2322: Type 'number' is not assignable to type 'string' respectivamente

Tipos en argumentos de función y valor de retorno. Cuerda

Ejemplo:

function hello(name: string): string {
    return `Hello ${name}!`;
}

Aquí el name: string sintaxis name: string significa que la función puede aceptar un argumento de name y este argumento solo puede ser cadena y (...): string { significa que el valor de retorno solo puede ser una cadena

Uso:

hello('StackOverflow Documentation') // will be return Hello StackOverflow Documentation!

Tipos de cuerdas literales

Los tipos literales de cadena le permiten especificar el valor exacto que puede tener una cadena.

let myFavoritePet: "dog";
myFavoritePet = "dog";

Cualquier otra cadena dará un error.

// Error: Type '"rock"' is not assignable to type '"dog"'.
// myFavoritePet = "rock";

Junto con los alias de tipo y los tipos de unión, obtienes un comportamiento similar a enumeración.

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");

Los tipos literales de cadena se pueden utilizar para distinguir las sobrecargas.

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)

Funcionan bien para los guardias de tipo definido por el usuario.

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();
    }
}

Código de ejemplo completo

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.

Tipos de interseccion

Un tipo de intersección combina el miembro de dos o más tipos.

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

Un Enum constante es lo mismo que un Enum normal. Excepto que no se genera ningún objeto en tiempo de compilación. En su lugar, los valores literales se sustituyen donde se utiliza el const Enum.

// 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]);

Para comparación, un Enum normal

// 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"


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow