I have a simple function that takes a function as it's argument and returns a new function. I get Object is of type 'unknown'
when calling the returned function
const makeFunction = <T>(callback: (someParam: number, options: T) => any) => { return (options: T) => { const param = 4; return callback(param, options) } }
Above code is okay for typescript but when I am calling function I get complaint
makeFunction((param, options) => { const a = options.optionsValue //(parameter) options: unknown, Object is of type 'unknown' })({optionsValue: 'some value'})
The "Object is of type unknown" error occurs when we try to access a property on a value that has a type of unknown . To solve the error, use a type guard to narrow down the type of the object before accessing a property, e.g. if (err instanceof Error) {} . Copied!
The "Type 'unknown' is not assignable to type" error occurs when we try to assign a value with a type of unknown to a value of a different type. To solve the error, use a type assertion or a type guard to verify that the two values have compatible types before the assignment.
Since this is the first result you get when you google Object is of type 'unknown'
, I want to post my case. It might help future readers. This is not the answer to OP's question.
I got this error in the catch
block. After debugging for a while I came to know that starting typescript v4.0, catch clause variables have type unknown
instead of any
.
And according to docs:
unknown is safer than any because it reminds us that we need to perform some sort of type-checks before operating on our values.
My code looked something like this before v4.0:
try { // try something exceptional here } catch (error) { console.log(error.message); }
And to fix this error, I had to put an additional if
check on error
variable.
try { // try something exceptional here } catch (error) { let errorMessage = "Failed to do something exceptional"; if (error instanceof Error) { errorMessage = error.message; } console.log(errorMessage); }
updating my tsconfig.json
with the following has worked for me:
"useUnknownInCatchVariables": false,
Update:
you need to put it like this under compilerOptions
"compilerOptions": { "useUnknownInCatchVariables": false }
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