-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type assertions using Exact, Subset, Superset #28586
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
Comments
Exact types #12936 |
Also #26064 |
Looking at this again, I think both const v = {foo:'bar'};
const vprime = Subset<T>v;
next we have Superset: const v = {foo:'bar', zoom:'zam'};
const vprime = Superset<T>v; Superset acts like an assertion: it asserts that vprime contains all the fields in |
Does this work? type Subset<L, R extends L> = L
type Superset<L extends R, R> = L
interface T {
foo: 'foo';
bar: 'bar';
}
const v: { foo: 'foo' } = {
foo: 'foo'
};
const v2: { foo: 'foo'; bar: 'bar', baz: 'baz' } = {
foo: 'foo', bar: 'bar', baz: 'baz'
};
const vprime1: Subset<typeof v, T> = v; // ok
const vprime2: Superset<typeof v, T> = v; // notok
const vprime2_1: Subset<typeof v2, T> = v2; // notok
const vprime2_2: Superset<typeof v2, T> = v2; // ok |
@jack-williams probably, except I am looking to use it with an anonymous object, like so: type T = ...
doMyThang((err, val) => {
res.json(<T>val.x);
}); it needs to be an assertion like that...AKA doing it this way instead kinda takes all my joy away: type T = ...
doMyThang((err, val) => {
const x : T = val.x; /// << superfluous code that I don't want to write or see
res.json(x);
}); Doing it with anonymous objects is the higher level goal I think. |
The subset type will allow creating true subsets of models to model things like partial DTOs and the like. Resolves microsoft#12936 (and microsoft#28586 to some extent)
I have suffered several times with the limitations of casting like so:
the above cast/assertion will work even if the anonymous object does not have all the fields in type
Foo
.For example, this question I had: https://stackoverflow.com/questions/53328459/prevent-compilation-unless-all-fields-exist
This feature request is for something like this:
note this is similar to the existing construct
Partial
, as inPartial<T>
, hopefully the above are self-explanatory. I am not sure if bothSubset<>
andSuperset<>
make sense, but one of them should.The text was updated successfully, but these errors were encountered: