Can I do this without a helper function?
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIhtAshAPAFWQF5kBnMKUAc2QB9kQBXAWwCNoA+ZAbwChkByMAE8ADhABcyfAG5+guFChxhU-AG0AunIC+vXgBMICADaKUMRiARhgAexDJQScMABuwAF558HABTAUuiYUDgEHACUQRjYPhxyvAD0icgA7sBgABZ2jGDImRAm4lDIlta2DvoIDuROMaGSaPU4xDzyAiLiUgBE5JQgVN0ANO3IisqqyOoAjEPIAExzAMyac8nIEn68ekkpVHZ2BvrOEK4e3n58gkJijb0U1MOj4ypS6t0vwsPI3XYw3-d+lRSN1VtsIgkTmcvBBLqNOo0ACyLZ5KV5TWYLZZgnQQ-TraBQOxQUjHaynWznWFXQQInp9R4ja6fN6YxbIFYjXGQ8nQi40jq3KTIpkKNGTd6fAF-AEMgYgnEQoA
I really don't like helper functions that do nothing in vanilla...is there any TS hack I can do to not need it?
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
7 Replies
what? just remove the errors?
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
or what are you trying to do?
I want
type
and array[number]
to be the same type. TS doesn't error when they're mismatched unless I pass the whole object to a helper function. Is there any way I can eliminate the need for the helper function while still having it error where I want it to?The solution is to pass in the generic needed;
If you don't pass the generic,
T
will always be string | number
, meaning type and array can have different types.
Even with the upcoming satisfies
keyword, this is still true.
I would recommend changing InferMe
to the following for two reasons;
1. extends
clause prevents someone from passing in InferMe<boolean>
or InferMe<SomeOtherInterface>
, I presume in your actual use case there is a limit on what may be used for T
, you should enforce that.
2. not providing a default type with =
will ensure that you always pass in a certain type, and never leave T
as "any of the many possibilities", i.e. the current situation you're facing.
By doing this, InferMe
now demands a type argument, and will ensure that if type is some specific type, the array is an array of that specific type also.
---
I experimented with readonly
and as const
, but the issue remains; one may be a string
while the other is a number
, because both of those are assignable to T
, which is string | number
interesting...well thanks
someone in another server got https://www.typescriptlang.org/play?ssl=14&ssc=3&pln=1&pc=1#code/C4TwDgpgBAkgdgMwgJwLIQDwBUoQB7ARwAmAzlABSnDICWcA5lAD5RwCuAtgEYoCUUALyVqdRizZdeyPgD4hUHPkIly9JMlhQA-FADeAKCjGooSAC5YAbiMmAhsmR2QlmAG0AujYC+US3AgANxQDAwBjAHs4aih1FHRXRHjoYUMTU3AISwAiUXoGbIAaW2MHJxcoNwBGQqgAJlqAZg9i7xtwqJi4tAg6xI10BTSTMyyoXJp8opKoMudLN2yqovG6lezG7JaDNqA to work 👀
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.