I believe that you are trying to explore generics and its usages. Perhaps the function that you have just shared is not really a good case study for generics. The first parameter of Math.pow is expected to be a number type, which is why you are getting the error. Imagine if you are invoking the function as such:
console.log(carre1<string>("abc"));
It will cause runtime error, which is why it was prevented by TS transpilation process in the first place.
If we look at the function from a functionality perspective, there is no need for it to be generic at all. It is understood to be a number already. The function could then be written as something like following, without generics:
function carre1(x: number): number {
x = Math.pow(x, 2);
.... some other logics?
return result;
}
However, if we insist on using generic parameter, perhaps the following can be considered. Though the generics are not being useful in this case:
function carre1<T>(x: T ): T {
let y:any = Math.pow(x as any, 2);
return y;
}
Consider this following function. It could be a useful example of Generics as the function should be able to accept parameter of any type. In another word, the function logic is type independent.
function deepCopy<T>(data: T): T {
return JSON.parse(JSON.stringify(data));
}
Another good use case of generics could be implementing a Data or Object Mapper. Refer to this example shared here https://stackoverflow.com/a/52759912/6096478