Home > Blockchain >  Generics - 'Type 'string' is not assignable to type 'T', even with typeof c
Generics - 'Type 'string' is not assignable to type 'T', even with typeof c

Time:12-13

Studying generics and I've reviewed this answer but don't understand why my hypothetical example throws a type error even with a typeof check.

My understanding is that this function would only return a string if a string is provided to it, so shouldn't that be type-safe?

function foo<T>(value: T):T {
    if(typeof value === 'string'){
        return value.toUpperCase() // Type 'string' is not assignable to type 'T'.
    }
    return value
}

CodePudding user response:

No, it is not type-safe.

Consider the following example:

const result = foo("a")
//    ^? const result: "a"

console.log(result) // [LOG]: "A" 

The return type of the function is "a", but it actually returns "A". We have created a mismatch between type and actual value. When dealing with primitives, you always have to consider that generic types may also be literal types.


Playground

  • Related