7 Replies
ErickO
ErickO•3y ago
what? just remove the errors?
ErickO
ErickO•3y ago
or what are you trying to do?
cobalt
cobaltOP•3y ago
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?
WillsterJohnson
WillsterJohnson•3y ago
The solution is to pass in the generic needed;
const inferMe: InferMe<string> = {
type: "string",
array: [1, 2, 3], // :(
};
const inferMe: InferMe<string> = {
type: "string",
array: [1, 2, 3], // :(
};
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;
interface InferMe<T extends string | number> {
type: T;
array: T[];
}
interface InferMe<T extends string | number> {
type: T;
array: T[];
}
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
cobalt
cobaltOP•3y ago
interesting...well thanks
Want results from more Discord servers?
Add your server