-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Generic type mismatch with Readonly<T> #18094
Comments
This is working as intended and is an effect of #16368. The type checker is pointing out that it is not safe to treat the |
This feels like it limits generics to the point where they're hardly useful anymore... What we're trying to model is a "Model" class that wraps some data handled by a JSON API: interface IModelData {
href : string; // All models have an href
}
class ModelBase<DataType extends IModelData> {
persist(data : Readonly<DataType>) {
return callToServer(data['href'], data);
}
}
interface IUserData extends IModelData {
username : string;
}
class User extends ModelBase<IUserData> {} What is the correct way to model this in TypeScript that allows proper typechecking? |
One way to model it is to have a non-generic base class: interface IModelData {
href : string; // All models have an href
}
abstract class ModelBase {
abstract persist(data: IModelData): void;
}
class GenericBase<DataType extends IModelData> extends ModelBase {
persist(data : Readonly<DataType>) {
return callToServer(data['href'], data);
}
}
interface IUserData extends IModelData {
username : string;
}
class User extends GenericBase<IUserData> {}
function fn(arg: typeof ModelBase) {};
fn(User); Another way is to not use interface IModelData {
href : string; // All models have an href
}
class ModelBase<DataType extends IModelData> {
persist(data : Readonly<DataType>) {
return callToServer(data['href'], data);
}
}
interface IUserData extends IModelData {
username : string;
}
class User extends ModelBase<IUserData> {}
function fn(arg: new() => ModelBase<IModelData>) {}
fn(User); With either approach you're ensuring that the |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
This feels like #16985 in a slightly different form.
/cc @ahejlsberg
TypeScript Version: 2.5.1, but probably broken since 2.4.1
Code
Expected behavior:
No compilation error.
Actual behavior:
The text was updated successfully, but these errors were encountered: