Home > other >  Typescript difference between T and "T extends unknown"
Typescript difference between T and "T extends unknown"

Time:05-03

In typescipt, what is the difference between between T and T extends unknown when used as type parameter. For example:

function check<T extends unknown>(x: T): T {
    return x;
}

vs

function check<T>(x: T): T {
    return x;
}

Is there any difference between them in terms of behaviour?

CodePudding user response:

I believe these are more or less equivalent:

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type

unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.

  • Related