Skip to content
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

Type compatibility #739

Closed
DanTsk opened this issue Oct 17, 2019 · 3 comments
Closed

Type compatibility #739

DanTsk opened this issue Oct 17, 2019 · 3 comments
Labels

Comments

@DanTsk
Copy link
Contributor

DanTsk commented Oct 17, 2019

Is there any way to check that two types are compatible? For example, when object literal compatible with interface definition in function argument.

@DanTsk
Copy link
Contributor Author

DanTsk commented Oct 17, 2019

Like this.

interface Named {
    name: string;
}

class Person {
    name: string;
}

let p: Named;
// OK, because of structural typing
p = new Person();

Is there any function/util to check that Person and Named types are compatible?

@dsherret
Copy link
Owner

See #357. Basically no because the compiler API does not expose that yet.

@ChristianIvicevic
Copy link

ChristianIvicevic commented Oct 17, 2019

Just chiming in to the question since I was curious. @DanTsk What is your actual intention with that compatibility check? Types in TS are transparent by default and Microsoft unfortunately hasn't implemented a dedicated opaque keyword. If you want to prevent this semantically wrong assignment in code, so even before writing a static analyzer, you can use a helper such as this:

type Opaque<T> = T & { readonly __opaque: unique symbol };

@dsherret dsherret closed this as completed Dec 7, 2019
@dsherret dsherret reopened this Apr 3, 2021
@dsherret dsherret closed this as completed Apr 3, 2021
Repository owner locked and limited conversation to collaborators Apr 3, 2021
Repository owner unlocked this conversation Apr 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants