-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Union type in a generic method is not always properly validated #51587
Comments
It's perfectly valid for the type argument to expand to This is working as intended. |
There's a secondary issue of The definition that does what you want is: class Field<DataType> {
static readonly literalField: Field<'A'|'B'> = new Field<'A'|'B'>();
static readonly numberField: Field<1|2> = new Field<1|2>();
static readonly mixedField: Field<'A'|'B'|1> = new Field<'A'|'B'|1>();
_instance!: DataType;
}
class WrongFieldFilter {
filter<T extends Field<unknown>>(field: T, value: T['_instance']): void {
console.log(value);
}
} |
Thank you both for the clarification. @RyanCavanaugh I've found your issue describing a similar problem #14829 type NoInfer<T> = [T][T extends any ? 0 : never];
class FieldFilter {
filter<DataType>(field: Field<DataType>, value: NoInfer<DataType>): void {
console.log(value);
}
} I've created another option based on the above : type FieldExactDataType<T> = T extends Field<infer U> ? U : never;
class FieldFilter {
filter<T extends Field<any>>(field: T, value: FieldExactDataType<T>): void {
console.log(value);
}
} |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
union literal generic method
π Version & Regression Information
All versions including night build 5.0.0-dev.20221118
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
When we provide as a generic method parameter a union of literals of the same type (eg. strings) TS doesn't validate parameter values against this union literals, but wider against the literal's type.
π Expected behavior
When provided a generic method parameter is a union of literals of the same type TS should validate this parameter against union literals and raise 2345 error when the passed parameter doesn't belong to this union.
The text was updated successfully, but these errors were encountered: