Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is of type 'unknown' typescript generics

Tags:

typescript

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'}) 
like image 532
Sam Avatar asked Feb 10 '20 13:02

Sam


People also ask

How do you fix object type of unknown typescript?

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!

Is not assignable to parameter of type unknown []'?

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.


2 Answers

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); } 
like image 121
Murli Prajapati Avatar answered Sep 22 '22 08:09

Murli Prajapati


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   } 
like image 41
Vikrant Bhat Avatar answered Sep 20 '22 08:09

Vikrant Bhat