TS v3.x brought new type: unknown
. But it's not very clear how to easily use this type instead of any
.
Example: you're using some 3rd party library which has no types. And you don't have time to write those types yourself. You need to handle some data provided by that library.
Before unknown
:
function handle(data: any) {
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator] === 'function') {
for (let x of data.arrayProp) {...}
}
}
With unknown
:
function handle(data: unknown) {
// this line gives TS error: `data` is unknown type
if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator]=== 'function') {
...
Most docs in internet are using kind of instanceof
ways to check what type data
has. But i'm not really interested what type data
has. Everything i want to know is if there's arrayProp
there. that's it
How to do this with unknown
type?
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
Use a user-defined type guard to check if a value with unknown type contains a property in TypeScript. The user-defined type guard consists of a function that checks if the specific property is contained in the object and returns a predicate.
In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type.
The "Property does not exist on type Object" error occurs when we try to access a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.
The thing with unknown
is that you have to narrow its type before you can use it. You can use a custom type guard for this:
interface ArrayProp {
arrayProp: []
}
function isArrayProps(value: unknown): value is ArrayProp {
return !!value && !!(value as ArrayProp).arrayProp;
}
function handle(data: unknown) {
if (isArrayProps(data) && typeof data.arrayProp[Symbol.iterator] === 'function') {
}
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With