Lod*_*din 5 generics typescript typescript-typings
I try to write typescript functions in the style that is most close to functional. For simple functions I can write:
type A = (value: number) => string;
const a: A = value => value.toString();
Run Code Online (Sandbox Code Playgroud)
But what can I do with generic types? How can I type in that simple way following function?
function a<T>(value: T): T {
return value;
}
Run Code Online (Sandbox Code Playgroud)
If I try to simply add a generic type, it gives nothing:
type A = <T>(value: T) => T;
const a: A = value => value; // `value` implicitly has an `any` type
Run Code Online (Sandbox Code Playgroud)
Is there any way to do it?
In your last snippet:
type A = <T>(value: T) => T;
const a: A = value => value;
Run Code Online (Sandbox Code Playgroud)
You tell the compiler that a is of type A, but you don't bind it to a specific generic type which is why it uses any.
For example, you can set the generic type like so:
const a: A = (value: string) => value;
Run Code Online (Sandbox Code Playgroud)
You can also do this:
type A<T> = (value: T) => T;
const a: A<string> = value => value;
Run Code Online (Sandbox Code Playgroud)
If you want a to be specific.
If you want a to stay generic you'll need to declare the generic constraint on it as well:
const a: A = <T>(value: T) => value;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5043 次 |
| 最近记录: |