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 tounknown
, butunknown
isn’t assignable to anything but itself andany
without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on anunknown
without first asserting or narrowing to a more specific type.