TypeScript 的强制类型转换

在 TypeScript 中将一个 number 转换成 string ,这样做会报错:

1var a:number = 12345;
2var b:string = <string> a;
3// laygroundSingle.ts(24,18): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.

这样写虽然不会报错,但没有什么卵用:

1var a:number = 12345;
2var b:string = <string><any> a;
3console.log(typeof b)
4// "number" PlaygroundSingle.js:19:1

还是直接用 javascript 的方法比较靠谱:

1var b:string = String(a);
2// or
3var b:string = a.toString();

注意 new String()String() 的区别:

 1var a:number = 12345;
 2// 使用 new 的时候类型必须是 String 而非 string ,否则无法编译通过
 3var b:String = new String(a);
 4// 不使用 new 则无所谓
 5var c:string = String(a);
 6console.log(a);
 7console.log('--------b');
 8console.log(typeof b);
 9console.log(b);
10console.log(b.length);
11console.log('--------c');
12console.log(typeof c);
13console.log(c);
14console.log(c.length);

结果如下:

112345 PlaygroundSingle.js:22:9
2"--------b" PlaygroundSingle.js:23:9
3"object" PlaygroundSingle.js:24:1
4String [ "1", "2", "3", "4", "5" ] PlaygroundSingle.js:25:9
55 PlaygroundSingle.js:26:9
6"--------c" PlaygroundSingle.js:27:9
7"string" PlaygroundSingle.js:28:1
8"12345" PlaygroundSingle.js:29:9
95

(全文完)