简体   繁体   中英

Typescript: Generic Type being inferred to Literal Type

Having an issue where " f<T>(val:T) {}; f(5); " is causing T to be a Literal Type of 5 instead of Number. Can I specify that I do not want a literal type here, as I want T to be a number (or any non literal) in this case?

extends number will do that for you, but also will block any number types

let f1 = <T extends number>(val: T) => val;
let result1 = f1(5); // 5
let result2 = f1(true) // Error

But adding map number into 5 will works for any type

let f2 = <T>(val: T) => val;
let result1 = f2(5 as 5) // 5

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