Unknown
If you write a function that only passes down an input to another function, use unknown
. From the perspective of the function: "I don't know, I don't wanna know". There is nothing wrong with using unknown
.
E.g.:
function buy(item: unknown): Purchase {
if (item) {
return purchase(item);
} else {
throw new TypeError('item is missing');
}
}
Any
If you need to call properties on that value, then any
is more suited.
Linting might not like any
, suggesting you to be more specific with your input. That way, if you change the interface from isItem
to isValid
, typescript tells you to update your code.
E.g.:
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function isItem(item: any): item is Purchase {
return !!item?.price;
}
Calling properties
function isStuff(item: unknown): item is Stuff {
return (item as Stuff).it !== undefined;
}
function isStuff(item: any): item is Stuff {
return item.it !== undefined;
}
camelcaseKeys(item) as unknown as Item;
See user defined guards if you're interested, I brought it in because it's one of the few cases where I need any.
From this blog from ultimatecourses:
Use the any
type when there are no other options
It's hard to find good examples for any
.
Anything is assignable to unknown, but unknown isn't assignable to anything but itself
sounds like rhyme – Snowberunknown
andany
are 2 special types that can hold any value in typescript. However,Unknown
is recommended overany
because it offers type checking whenever we try to use the variable. – Forewingunknown
toany
– Gronseth