简体   繁体   中英

What is the meaning of `const func: (num: number) => string = String;` in TypeScript?

I am reading 2ality blog post on TypeScript and I came across the following code -

const func: (num: number) => string = String;

I don't understand the meaning of this syntax.

In TypeScript Playground , it compiles to -

var func = String;

From what I understand, func is a function which takes a parameter num and the function itself returns a string and the func variable is assigned to String so the whole function thing becomes useless which means the above thing could've been written as simple as -

const func = String;

Am I correct? Or am I understanding Typescript wrong?

const func: (num: number) => string = String;

This means there is a variable func whose type is (num: number) => string with value as String class.

Now string constructor accepts a value and returns a string value.


For people that are confused between string and String

  • string : refers to string value. So () => string means a function returning a string. In var a = 'abc' , a is a string
  • String : Note capital S . That refers to string constructor, which is a function.

Following is the definition of String : 在此输入图像描述

It's a function which converts a passed Number to a String .

You can see that if you enter the following TypeScript:

const func: (num: number) => string = String;
console.log(func(123));
console.log(typeof func(123));
console.log(typeof 123);

It compiles to:

var func = String;
console.log(func(123));
console.log(typeof func(123));
console.log(typeof 123);

And executing this code shows 123 , string and number :

 var func = String; console.log(func(123)); console.log(typeof func(123)); console.log(typeof 123); 

So, func in the above example is returning new String(num) , which is why 123 is a number, but func(123) is a string.

It is basically saying func is a function (denoted by x => y ) which takes variable named num of type number as input, and returns a string . In this case the value of function is assigned to the function String , which is a constructor function.

In the end, func is a new name given to String constructor such that it only accepts numeric input. So func(5) would be equivalent to String(5) and it would return "5".

Notice that the string (num: number) => string denotes the schema of function being declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM