#narrowing
16 messages · Page 1 of 1 (latest)
Show some more code, a playground reproduction would be best.
1st print no error. 2nd print there is an error because of narrowing. how do i ensure i always have the 2nd one where elem can only be an element in array
That's expected behavior, your test2 now doesn't fit the Test type.
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
So you want your elem can only be values from array?
yes
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.
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')
...```