Limboer
Limboer

Reputation: 414

Different ways of declaring function type in typescript?

I find in typescript you can simply declare a function type using declare keyword, for example:

declare function test1(name: string): true

const t1 = test1('t') // true

and i can also do this using the arrow notation:

const test2 = (name: string) => true

const t2 = test2('t') // boolean

Both of them works fine without any compiler error. But it seems like the final inferred type is different even i specific them to be true at the same time?

Meanwhile, if i change the return type true to a general primitive type, for example string, the second example will give me an error:

declare function test1(name: string): string // ok

const test2 = (name: string) => string // error: 'string' only refers to a type, but is being used as a value here.

It looks like for the "arrow function notation" type, you have to specify the return result/type to be a specific result, for example, generic does not make sense as well if you put it into the final result:

declare function test1<T>(name: T): T // ok

const test2 = <T>(name: T) => T // error: 'T' only refers to a type, but is being used as a value here.

However, both of them does not "looks like a type", what i mean this is you are able to define them using const keyword(in second example, usually this is for declaring a variable from my knowledge), and you can then call them like a normal function, it will give you the return type/result without implement the actual detail:

test1('xxx')
test2('xxx')

So my question would be:

Upvotes: 0

Views: 2178

Answers (1)

Lauren Yim
Lauren Yim

Reputation: 14078

When you declare something, it just tells the TypeScript compiler that there will be that function/variable/class etc. at runtime and is removed during compilation. You specify the type (or function signature for a function) of that thing:

// these are the same
declare function test1(name: string): true
declare const test1: (name: string) => true
test1('') // true

What you did with test2 is you created an arrow function that will exist at runtime because you didn't use the declare keyword and provided the implementation:

// these are also the same
function test2(name: string) {
  return true
}
const test2 = (name: string) => true
test2('') // boolean

As the return type is not explicitly stated, TypeScript infers the return type to be of boolean. To specify that it is true:

function test3(name: string): true {
  return true
}
const test3 = (name: string): true => true
test3('') // true

Upvotes: 2

Related Questions