#Check if a non primitive value is part of an Array

24 messages · Page 1 of 1 (latest)

true stag
#

I have an array of css hex colors called backgroundColors. renderButtons functions (can take buttons: TargetType[] | CustomizationOption[]) I would like to have something like
js const isBackground = (value: unknown | BackgroundColorCSSValue): value is BackgroundColorCSSValue => backgroundColors.includes(value) to check if the received parameter is a background color or other thing, but I'm having this error (see attached image). What can I do to avoid the error on backgroundColors.includes(value)

Thanks in advance!

#

Check if a non primitive value is part of an Array

old dock
#

@true stag this is actually a scenario where casting value to BackgroundColorCSSValue is not problematic

#

also, unknown | is useless

true stag
#

@old dock you mean something like this?

twin cloak
#

@true stag Just to be clear, when you say "non-primitive", the background colors are all primitives, right?

#

It's just that you're checking with something that may or may not be a primitive?

true stag
# old dock yes

I thought that casting values was not something good to do

twin cloak
#

You could also use:

#

!*:includes

minor wrenBOT
#
Retsam19#2505
`!retsam19:includes`:

The type of Array.prototype.includes assumes that you're using the string to check something about the array. If you're trying to do the reverse, a modified type signature is useful:

function includes<S extends string>(haystack: readonly S[], needle: string): needle is S {
    const _haystack: readonly string[] = haystack;
    return _haystack.includes(needle)
}

declare const x: string;
if(includes(["a", "b", "c"], x)) {
    // x is "a" | "b" | "c"
}
twin cloak
#

Or some variant of it, probably.

true stag
#

Thanks @twin cloak I will have a look into that later

#

But yeah, I feel like I've been using casting to solve many issues in my code base so I'm sure I'm not doing something propperly

twin cloak
#

Yeah, it depends - sometimes there's a cleaner, non-casting alternative, but not always.

#

It can also just be a "how much time are you willing to spend fighting this" - when you're newer to TS especially, it can be good to just put the cast in and move on rather than spending a long time fighting the type checker over every little thing.

true stag
#

I will like to share a repo and it would be great if you can givme feedback, and to check if I'm not having an elefant in te room

#

It's a tiny app, don't worry

#

Just to check if I'm not missing something important regarding TS

twin cloak
#

Sure I can take a look

old dock