Typescript OR in Function Intake

45 Views Asked by At

I am trying to tell my function to accept either a string or a custom type

onPress: (value: string | CustomType)=>void

however when I assign it a string or CustomType the compiler yells at me with is not assignable to type '(value: string | CustomType ) => void'

How can I fix it?

1

There are 1 best solutions below

0
Bart Hofland On BEST ANSWER

It seems to me, that you are mistaken regarding the type of your onPress variable. It is not of type string | CustomType, but of type (value: string | CustomType) => void. That type represents a function that takes a single argument of type string or CustomType and does not return anything.

You could assign an existing function to onPress:

type CustomType = number  // just for testing purposes
let onPress: (value: string | CustomType) => void

function doSomething(value: string | CustomType) {
  console.log("Doing something here with value " + value)
}

onPress = doSomething

onPress("BY432")

Or you could assign it an anonymous function:

type CustomType = number  // just for testing purposes
let onPress: (value: string | CustomType) => void

onPress = function (value) {
  console.log("Doing something here with value " + value)
}

onPress("BY432")

Or you could assign it an arrow function (also anonymous):

type CustomType = number  // just for testing purposes
let onPress: (value: string | CustomType) => void

onPress = value => console.log("Doing something here with value " + value)

onPress("BY432")