LoginSignup
5
5

More than 5 years have passed since last update.

TypeScriptについてのいくつかのnote

Last updated at Posted at 2015-11-02

TypeScriptを使って気づいた点、調べてもあまり情報が出てこなかった点をまとめます。
初心者なので、おかしい点があれば指摘をお願いします。

使用したバージョンは 1.6.2 です。

演算子による暗黙の型変換は警告されない場合がある

通常、TypeScriptでは異なる型同士の演算はエラーになります。

const one:number[] = [1];
const two:number = 2;
const three:boolean = false;

console.log(one + two); // error TS2365: Operator '+' cannot be applied to types 'number[]' and 'number'.
console.log(two + three); // error TS2365: Operator '+' cannot be applied to types 'number' and 'boolean'.

しかし、一部の演算による型変換はエラーになりませんし、警告もされません。以下のコードはコンパイルを通ります。

const one:string = '1';
const two:number = 2;
const three:boolean = false;

console.log(one + two + three); // -> '12false'
console.log(!!one); // -> true
console.log(+one); // -> 1

Rest Parameters で渡した引数は型推論されない

以下のコードはコンパイルが通ります。

function sum(...numbers:number[]):number {
    return numbers.reduce((previous, current) => {
        return previous + current;
    }, 0);
}

function sumTwo(A, B):number {
    return sum(A, B);
}

console.log(sumTwo('1', '2')); // -> '012'

sumTwoからsumに渡した引数が型推論されず、any型で通ってしまうからです。コンパイルオプションにnoImplicitAnyを加えると警告されます。

その他の型推論されない例

ML系の型推論に慣れていると忘れがちですが、以下のような例はすべて型推論されません。

let hoge; // any
hoge = 'fuga';

// 追記: v2.1.1で型推論されるようになりました。
function hoge(num /*any*/):number {
    return num;
}
((hoge /*any*/) => {
    console.log(hoge);
})('string')

// 追記: v2.0.9で型推論されるようになりました。

連想配列として宣言した変数には、[]でしかアクセスできない

JavaScriptでは、以下のコードは完全に等価です。

hash['key'] = 334;
hash.key = 334;

一方TypeScriptでは、Objectを連想配列として使用するために、以下のような宣言が認められています。

const hash:{[id:string]:number} = Object.create(null);

このように宣言した連想配列は、[]でしかアクセスできなくなります。つまり、JavaScriptで等価だったコードは等しくなくなります。

hash['key'] = 334;
hash.key = 334; // error TS2339: Property 'key' does not exist on type '{ [id: string]: number; }'.
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5