#narrowing

16 messages · Page 1 of 1 (latest)

ashen spindle
#

how can i make sure i have a type that is an item that exists in the array. this works, but i have to make sure the array is narrowed. how can i ensure arrays are narrowed whenever i use this?

type Extract<T extends string[]> = {
  array: T;
  elem: T[number];
}
zenith steeple
#

Show some more code, a playground reproduction would be best.

zenith steeple
#

That's expected behavior, your test2 now doesn't fit the Test type.

ashen spindle
#

how can i ensure test becomes like test2 with always having to specify as const

#

is there anything i can do in the type

#

test is bad because i can use any string for the elem

zenith steeple
#

So you want your elem can only be values from array?

ashen spindle
#

yes

zenith steeple
#

I don't see an ergonomic way to do it if you want to avoid manually type annotating things, other than using a factory function.

tame solsticeBOT
#
Burrito#6903

Preview:```ts
type Test<T extends string[]> = {
array: T;
elem: T[number];
}

function print<T extends string[]>(test: Test<T>) {
console.log(test);
}

function createTest<const T extends string>(array: T[], elem: T & {}) {
return { array, elem }
}

const test1 = createTest(['hello'], '1')
...```

ashen spindle
#

ok ty

#

is what i have still okay to use if i make sure my array types are narrowed?

#

my other option is just throwing the generic out and just using the type. so string[] and string

zenith steeple
#

🤷‍♂️

#

Depends on how much you care about the correctness of "elem must be in array"