Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How to write a conditional promise.resolve properly in typescript?

$
0
0

I have a project in react native using typescript and I would like to use Promise.resolve().then() of an object with a condition which causing a type error in typescript. Below is the situation:

I have the first object (as sample):

const objectA = {   a: 1,   b: 2,}

And I have my second object (as sample):

const objectB = {   c: 3,   d: 4,   e: 5,}

So both objects have different types and keys with value. Here is the problem, I have a condition to check which object to be resolve based on some host type, e.g.:const objectTobeResolved = type === 'primary' ? objectA : objectB

So based on that condition, I pass it to the Promise:

const someFunction = () => {   Promise.resolve(objectTobeResolved).then((values) => { ... })}

I will get the type error here in the typescript for objectTobeResolved something like this:

TS2345: Argument of type 'Promise<{ c: number; d: number; e: number; }> | Promise<{ a: number; b: number; }>' is not assignable to parameter of type '{ c: number; d: number; e: number; } | PromiseLike<{ c: number; d: number; e: number; }>'.   Type 'Promise<{ a: number; b: number; }>' is not assignable to type '{ c: number; d: number; e: number; } | PromiseLike<{ c: number; d: number; e: number; }>'.Type 'Promise<{ a: number; b: number; }>' is not assignable to type 'PromiseLike<{ c: number; d: number; e: number; }>'.Types of property 'then' are incompatible.Type '<TResult1 = { a: number; b: number; }, TResult2 = never>(onfulfilled?: ((value: { a: number; b: number; }) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type '<TResult1 = { c: number; d: number; e: number; }, TResult2 = never>(onfulfilled?: ((value: { c: number; d: number; e: number; }) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => PromiseLike<...>'.Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.Types of parameters 'value' and 'value' are incompatible.Type '{ a: number; b: number; }' is missing the following properties from type '{ c: number; d: number; e: number; }': c, d, e

Basically the required type here is objectA | objectB, but I actually only need to pass one of the object based on the condition above. I don't quite understand how to declare it properly in typescript.

What is a right way to write the promise here? should I use race or all instead? But I only need to check one object at a time. Or should I declare or initialise in a certain way?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>