サーチ…


構文

  • let variableName:VariableType;
  • 関数functionName(parameterName:VariableType、parameterWithDefault:VariableType = ParameterDefault、optionalParameter?:VariableType、... variardicParameter:VariableType []):ReturnType {/*...*/};

ブール

ブール値は、True / False値を割り当てる目的で、TypeScriptの最も基本的なデータ型を表します。

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

JavaScriptと同様に、数値は浮動小数点値です。

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

ECMAScript 2015では、バイナリと8進数を使用できます。

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

文字列

テキスト形式:

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

アレイ

値の配列:

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

列挙型

1組の数値の名前を指定する型。

数値の既定値は0です。

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

デフォルトの開始番号を設定する:

enum TenPlus { Ten = 10, Eleven, Twelve }

または値を割り当てる:

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

どれか

タイプが不明なanyは、次のanyを使用できます。

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

型を全く持たない場合、何も返さない関数によく使用されます:

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

voidnullまたはundefinedのみを割り当てることができます。

タプル

既知の、おそらく異なるタイプの配列型

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'

関数の引数と戻り値の型。数

TypeScriptで関数を作成するときには、関数の引数のデータ型と戻り値のデータ型を指定できます

例:

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

ここで、 x: number, y: numberという構文は、関数が2つの引数xyを受け入れることができることを意味し、数字と(...): number {のみであることができます(...): number {戻り値が数字

使用法:

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

注意:

あなたはそうすることはできません

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

または

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

次のエラーが表示されます。

error TS2322: Type 'string' is not assignable to type 'number'error TS2322: Type 'number' is not assignable to type 'string'それぞれerror TS2322: Type 'number' is not assignable to type 'string'

関数の引数と戻り値の型。文字列

例:

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

構文name: stringは、関数が1つのname引数を受け入れることができることを意味し、この引数はstringおよび(...): string {のみであることができ(...): string {戻り値が文字列

使用法:

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

文字列型

文字列型では、文字列が持つことができる正確な値を指定できます。

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

他の文字列ではエラーが発生します。

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

タイプエイリアスとユニオンタイプと一緒にenumのような動作が得られます。

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

文字列リテラルタイプは、過負荷を区別するために使用できます。

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)

ユーザー定義型ガードの場合はうまく機能します。

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

完全なコード例

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.

交差点タイプ

交差型は、2つ以上の型のメンバーを結合します。

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は通常のEnumと同じです。コンパイル時にオブジェクトが生成されない点を除きます。代わりに、定数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]);

比較のために、通常の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"


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow