0
let entities: {
  clickPrice: number
} | undefined = Math.random() >= 0.5 ? {
  clickPrice: Math.random()
} : undefined

const clickPrice = Math.random() >= 0.5 ? Math.random() : undefined

type testType = {
  clickPrice: number
}

const test: {
  clickPrice: number
}[] = []

if (entities || clickPrice) {
  test.push({
    clickPrice: entities ? entities.clickPrice : clickPrice
  })
}

Why do I get this error:

Type 'number | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.

on clickPrice

clickPrice: entities ? entities.clickPrice : clickPrice

?
What I want is "If there's entities, or clickPrice, execute some code, which could use only one of them".
TS playground

3 Answers 3

3

In the section on type narrowing (specifically "control flow analysis"), you can see how TypeScript handles types. In short, TypeScript can narrow entities, and it can narrow clickPrice, but it can't narrow the expression entities || clickPrice in a way that is helpful to you.

You'll have to break it out, at minimal expense to readability:

if (entities) {
  test.push({clickPrice: entities.clickPrice});
} else if (clickPrice) {
  test.push({clickPrice});
}

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

0

Because your type clearly defines this property as number only:

type testType = {
  clickPrice: number
}

However, your code states that if the random number (0-1) is bigger than 0.5, do another random or return undefined if it's not:

const clickPrice = Math.random() >= 0.5 ? Math.random() : undefined

You need to either update the type to support undefined or return a valid number instead.

2 Comments

But I push only if there's no undefined - either entities(with required clickPrice), or clickPrice itself. If they're both undefined, code never executes
Try console.log('test', test) at the end of code block - you'll see, that sometimes it's empty array([])
0

You need to use as as number for clickPrice because it might be undefined.

if (entities || clickPrice) {
  test.push({
    clickPrice: entities ? entities.clickPrice : clickPrice as number
  })
}

Here is working one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.