Examples of mandatory type conversions for typescript

Source: Internet
Author: User

Forced type conversions for typescript


Converting a number to a string in typescript will cause an error:

var a:number = 12345;
var b:string = <string> A;
Laygroundsingle.ts (24,18): Error ts2352:neither type ' number ' nor type ' string ' is assignable to the other.

This writing is not an error, but there are no eggs to use:

var a:number = 12345;
var b:string = <string><any> A;
Console.log (typeof B)
"Number" playgroundsingle.js:19:1
Or is it straightforward to use JavaScript in the right way:

var b:string = string (a);
Or
var b:string = a.tostring ();
Notice the difference between the new string () and string ():

var a:number = 12345;
When using new, the type must be string instead of string, or it cannot be compiled through
var b:string = new String (a);
It doesn't matter if you don't use new
var c:string = string (a);
Console.log (a);
Console.log ('--------b ');
Console.log (typeof B);
Console.log (b);
Console.log (b.length);
Console.log ('--------c ');
Console.log (typeof c);
Console.log (c);
Console.log (c.length);

The results are as follows:

12345 Playgroundsingle.js:22:9
"--–b" Playgroundsingle.js:23:9
"Object" Playgroundsingle.js:24:1
String ["1", "2", "3", "4", "5"] Playgroundsingle.js:25:9
5 Playgroundsingle.js:26:9
"--–c" Playgroundsingle.js:27:9
"String" Playgroundsingle.js:28:1
"12345" Playgroundsingle.js:29:9
5
(End of full text)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.