microsoft / typespec

https://typespec.io/
MIT License
4.56k stars 222 forks source link

Self Referencing Generics only work when optional #1816

Open NielsCo opened 1 year ago

NielsCo commented 1 year ago

The following TypeSpec Code:

model MyModel<T extends MyModel<T>> {
    // otherProperties
    link: T;
}

model ExtendsMyModel extends MyModel<ExtendsMyModel> {
  // some other properties
}

Throws the following Error: error missing-property Property 'link' is missing on type 'ExtendsMyModel' but required in 'MyModel<T>' Playground Link

Making the link-property optional makes it work though:

model MyOptionalModel<T extends MyOptionalModel<T>> {
    // otherProperties
    link?: T;
}

model ExtendsMyOptionalModel extends MyOptionalModel<ExtendsMyOptionalModel> {
  // some other properties
}

Playground Link

Maybe this has to do with the warning in the interface docs

timotheeguerin commented 1 year ago

interesting, from looking at the error this seems to be due to the override check for model extends that check properties in derived models are compatible with the base model

markcowl commented 1 year ago

@NielsCo Can you elaborate on the scenario where you would use this sort of API definition?

NielsCo commented 1 year ago

Sure. If I someone wanted to model a tree data-structure they could create a model like this. With the "link" property being the parent-node. And the need for generics because there are multiple node-types. Which obviously only is a good idea if the tree structure is and (will forever be) small enough to be transmitted via an endpoint.

I probably should have elaborated that for me the issue is not a blocker, as I was just trying out TypeSpec and noticed that this feature I know from other languages didn't work as I expected it to. Especially the part that the property being optional did not cause an error, looked like an interesting issue to me

markcowl commented 1 year ago

Thanks, that helps. Definitely an issue we want to fix, but this helps us weigh the priority