Re:Ink: React for Interactive CLI Apps
by Capricorn2481 on Saturday November 02, 2024 @11:15AM
(#42026867)
To me this is expected? Thing is supposed to be one or the other. If I wanted a homogeneous array I would use a generic <T> for the add function, which makes more sense for a function that just pushes to an array anyway.
[ Parent
| on HN ]
Re:Ink: React for Interactive CLI Apps
by trenchgun on Saturday November 02, 2024 @04:14PM
(#42028945)
arr was defined to be an array of strings. How are you pushing a boolean there?
Re:Ink: React for Interactive CLI Apps
by Capricorn2481 on Sunday November 03, 2024 @04:11PM
(#42036122)
Because you've given the function no information on whether those two "things" are related. You're saying when it gets passed into that function it can be treated as either with type widening.
I understand it may be unwanted at first glance, but this is a contrived example for demo purposes. You wouldn't really make an "add to array" function like this so specifically. You would use generics, which would solve the exact issue that is posed.
function add<T>(item: T, dst: T[]): void {
dst.push(item);
}
Now you can work with any array, and it will only add items with the right type.If you really need it to be just <Thing>, you can do this
function add<T extends Thing>(item: T, dst: T[]): void {
dst.push(item);
}
Now it knows that Item and DST are related but need to be Thing.