I've noticed that in Typescript you can easily declare a function type using the declare
keyword. For example:
declare function test1(name: string): true
const t1 = test1('t') // true
Alternatively, you can also use the arrow notation:
const test2 = (name: string) => true
const t2 = test2('t') // boolean
Both of these methods work perfectly fine without any compiler errors. However, it seems like the final inferred type is different even when specifying them to be true
at the same time?
On the other hand, if I change the return type true
to a general primitive type, such as 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 appears that for the "arrow function notation" type, you need to specify the return result/type to be a specific result. Using generics does not make sense either for 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, neither of them "looks like a type" in the sense that you can define them using the const
keyword (in the second example, which is usually for declaring a variable). You can then call them like a normal function, and they will give you the return type/result without implementing the actual details:
test1('xxx')
test2('xxx')
So my question is:
- Are they truly types (like type aliases)? Do they have specific names in Typescript?
- Is there any distinction between these two notations? How should we properly use them?