Exact Types #12936
Exact Types #12936
Comments
I would suggest the syntax is arguable here. Since TypeScript now allows leading pipe for union type. class B {}
type A = | number |
B Compiles now and is equivalent to I think this might not I expect if exact type is introduced. |
Not sure if realted but FYI #7481 |
If the type Exact<T> = {|
[P in keyof T]: P[T]
|} and then you could write |
This is probably the last thing I miss from Flow, compared to TypeScript. The |
@HerringtonDarkholme Thanks. My initial issue has mentioned that, but I omitted it in the end as someone would have a better syntax anyway, turns out they do @DanielRosenwasser That looks a lot more reasonable, thanks! @wallverb I don't think so, though I'd also like to see that feature exist |
What if I want to express a union of types, where some of them are exact, and some of them are not? The suggested syntax would make it error-prone and difficult to read, even If extra attention is given for spacing: |Type1| | |Type2| | Type3 | |Type4| | Type5 | |Type6| Can you quickly tell which members of the union are not exact? And without the careful spacing? |Type1|||Type2||Type3||Type4||Type5||Type6| (answer: |
@rotemdan See the above answer, there's the generic type |
There's also the concern of how it would look in editor hints, preview popups and compiler messages. Type aliases currently just "flatten" to raw type expressions. The alias is not preserved so the incomperhensible expressions would still appear in the editor, unless some special measures are applied to counteract that. I find it hard to believe this syntax was accepted into a programming language like Flow, which does have unions with the same syntax as Typescript. To me it doesn't seem wise to introduce a flawed syntax that is fundamentally in conflict with existing syntax and then try very hard to "cover" it. One interesting (amusing?) alternative is to use a modifier like function test(a: only string, b: only User) {}; That was the best syntax I could find back then. Edit: function test(a: just string, b: just User) {}; (Edit: now that I recall that syntax was originally for a modifier for nominal types, but I guess it doesn't really matter.. The two concepts are close enough so these keywords might also work here) |
I was wondering, maybe both keywords could be introduced to describe two slightly different types of matching:
Nominal matching could be seen as an even "stricter" version of exact structural matching. It would mean that not only the type has to be structurally identical, the value itself must be associated with the exact same type identifier as specified. This may or may not support type aliases, in addition to interfaces and classes. I personally don't believe the subtle difference would create that much confusion, though I feel it is up to the Typescript team to decide if the concept of a nominal modifier like (Edit: just a note about |
@ethanresnick Why do you believe that? |
This would be exceedingly useful in the codebase I'm working on right now. If this was already part of the language then I wouldn't have spent today tracking down an error. (Perhaps other errors but not this particular error |
I don't like the pipe syntax inspired by Flow. Something like exact interface Foo {} |
@mohsen1 I'm sure most people would use the |
With I think interface Foo {}
type Bar = exact Foo |
Exceedingly helpful for things that work over databases or network calls to databases or SDKs like AWS SDK which take objects with all optional properties as additional data gets silently ignored and can lead to hard to very hard to find bugs |
@mohsen1 That question seems irrelevant to the syntax, since the same question still exists using the keyword approach. Personally, I don't have a preferred answer and would have to play with existing expectations to answer it - but my initial reaction is that it shouldn't matter whether The usage of an |
We talked about this for quite a while. I'll try to summarize the discussion. Excess Property CheckingExact types are just a way to detect extra properties. The demand for exact types dropped off a lot when we initially implemented excess property checking (EPC). EPC was probably the biggest breaking change we've taken but it has paid off; almost immediately we got bugs when EPC didn't detect an excess property. For the most part where people want exact types, we'd prefer to fix that by making EPC smarter. A key area here is when the target type is a union type - we want to just take this as a bug fix (EPC should work here but it's just not implemented yet). All-optional typesRelated to EPC is the problem of all-optional types (which I call "weak" types). Most likely, all weak types would want to be exact. We should just implement weak type detection (#7485 / #3842); the only blocker here is intersection types which require some extra complexity in implementation. Whose type is exact?The first major problem we see with exact types is that it's really unclear which types should be marked exact. At one end of the spectrum, you have functions which will literally throw an exception (or otherwise do bad things) if given an object with an own-key outside of some fixed domain. These are few and far between (I can't name an example from memory). In the middle, there are functions which silently ignore Clearly the "will throw if given extra data" functions should be marked as accepting exact types. But what about the middle? People will likely disagree. Violations of Assumptions / Instantiation ProblemsWe have some basic tenets that exact types would invalidate. For example, it's assumed that a type It's also assumed that MiscellanyWhat is the meaning of Often exact types are desired where what you really want is an "auto-disjointed" union. In other words, you might have an API that can accept Summary: Use Cases NeededOur hopeful diagnosis is that this is, outside of the relatively few truly-closed APIs, an XY Problem solution. Wherever possible we should use EPC to detect "bad" properties. So if you have a problem and you think exact types are the right solution, please describe the original problem here so we can compose a catalog of patterns and see if there are other solutions which would be less invasive/confusing. |
@heystewart Your let a: Exact< { foo: number }[], { foo: number, bar?: string }[] >;
let b: Exact< { foo: number, bar?: string }[], { foo: number }[] >;
a = [{ foo: 123, bar: 'bar' }]; // error
b = [{ foo: 123, bar: 'bar' }]; // no error Edit: @ArnaudBarre's version also has the same issue |
@papb Yes effectively my typing doesn't work is the entry point is an array. I needed it for our graphQL API where To solve it you need to isolated ExactObject and ExactArray and have an entry point that goes into one or the other. |
So what the best way to make sure that object has exact properties, no less, no more ? |
@captain-yossarian convince TypeScript team to implement this. No solution presented here works for all expected cases, and almost all of them lack clarity. |
@toriningen can't imagine how many issues will be closed if TS team will implement this feature |
@RyanCavanaugh
Those immediate goals serve these ends:
ExampleI have reduced my case to this: type X = {
red?: number,
green?: number,
blue?: number,
}
function y<
Y extends X
>(
y: (X extends Y ? Y : X)
) {
if ((y as any).purple) throw Error('bla')
return y as Y
}
const z = y({
blue: 1,
red: 3,
purple: 4, // error
})
z.green // error
type Z = typeof z That setup works and accomplishes all the desired goals, so from a pure feasibility standpoint and so far as this goes, I'm good. However, EPC is achieved through the parameter typing ProposalAnd that is why I'd like to have an type X = {
red?: number,
green?: number,
blue?: number,
}
function x<
Y implements X
>( y: Y ) {
if ((y as any).purple) throw Error('bla')
return y as Y
}
const z = y({
blue: 1,
red: 3,
purple: 4, // error
})
z.green // error
type Z = typeof z This seems far clearer to me than my current workaround. Apart from being more concise, it locates the whole constraint with the generics declaration as opposed to my current split between the generics and the parameters. That may also enable further use-cases that are currently impossible or impractical, but that is presently only a gut feeling. Weak Type Detection as an AlternativeNotably, Weak Type Detection as per #3842 should fix that just as well, and might be favorable on account of not requiring additional syntax, if it worked in connection with Regarding
|
I have an immature idea About type annotations. Matching an object is divided into members can be exactly equal, no more and no less, more or less, no more but less, more but no less. For each of the above cases, there should be one expression. exactly equal, i.e. no more and no less: function foo(p:{|x:any,y:any|})
//it matched
foo({x,y})
//no match
foo({x})
foo({y})
foo({x,y,z})
foo({}) more but no less: function foo(p:{|x:any,y:any, ...|})
//it matched
foo({x,y})
foo({x,y,z})
//no matched
foo({x})
foo({y})
foo({x,z}) no more but less: function foo(p:{x:any,y:any})
//it matched
foo({x,y})
foo({x})
foo({y})
//no match
foo({x,z})
foo({x,y,z}) more or less: function foo(p:{x:any,y:any, ...})
//it matched
foo({x,y})
foo({x})
foo({y})
foo({x,z})
foo({x,y,z}) conclusion:With a vertical line indicates that there is no less, without a vertical line means that there can be less. With an ellipsis sign means that there can be more, without an ellipsis sign means that there can be no more. Arrays match is the same idea. function foo(p:[|x,y|]) // p.length === 2
function foo(p:[|x,y, ... |]) // p.length >= 2
function foo(p:[x,y]) // p.length >= 0
function foo(p:[x,y,...]) // p.length >= 0 |
@rasenplanscher using your example, this compiles:
However with exact types, it should not. I.e. the ask here is to not depend on EPC. |
@xp44mm "more but no less" is already the behaviour and "more or less" is the behaviour if you mark all properties optional function foo(p:{x?: any, y?: any}) {}
const x = 1, y = 1, z = 1
// all pass
foo({x,y})
foo({x})
foo({y})
const p1 = {x,z}
foo(p1)
const p2 = {x,y,z}
foo(p2) Similarily, if we had exact types, exact type + all properties optional would essentially be "no more but less" . |
Another example to this issue. A good demonstration for this proposal I think. In this case I use someMethod(): Observable<MyType> {
const subject = new Subject<MyType>();
// This works, but should not. (if this proposal is implemented.)
return subject;
// Only Observable should be allowed as return type.
return subject.asObservable();
} I always want only return the exact type Proposal: // Adding exclamation mark `!` (or something else) to match exact type. (or some other position `method(): !Foo`, ...)
someMethod()!: Observable<MyType> {
// ...
} But I'm sure you have better ideas. Especially because this does not only affects return values, right? Anyway, just a pseudo code demo. I think that would a nice feature to avoid errors and lacks. Like in the case described above. Another solution could be adding a new Utility Type. |
Hi, I'm not sure where this is at, but this seems like a key feature that's missing. I made a playground but I think everyone here knows the issue. I think the best solution is adding a flag, similar to the |
Perhaps TypeScript doesn't have support for exact object types, but one could still validate that some type matches some other type exactly: type Exact<T, U> = T extends U
? Exclude<keyof T, keyof U> extends never
? T
: never
: never This can be used like this: interface Point {
x: number
y: number
}
function addPoints<A, B>(a: Exact<A, Point>, b: Exact<B, Point>): Point {
// add the points as vectors...
} |
@migueloller It would not be a 4 years old issue if it was that simple ;) playground |
@ArnaudBarre, we can leverage recursive types to fix this: Playground type Exact<T, U> = T extends Record<string, unknown>
? T extends U
? Exclude<keyof T, keyof U> extends never
? { [K in keyof U]: Exact<T[K], U[K]> }
: never
: never
: T |
It's still not that easy. Playground |
@lazytype, @ArnaudBarre, I'm seeing now the older comments (GitHub was hiding them because the discussion is so long). Sorry for re-stating what was already obvious/had already been explored. |
This is a proposal to enable a syntax for exact types. A similar feature can be seen in Flow (https://flowtype.org/docs/objects.html#exact-object-types), but I would like to propose it as a feature used for type literals and not interfaces. The specific syntax I'd propose using is the pipe (which almost mirrors the Flow implementation, but it should surround the type statement), as it's familiar as the mathematical absolute syntax.
This syntax change would be a new feature and affect new definition files being written if used as a parameter or exposed type. This syntax could be combined with other more complex types.
Apologies in advance if this is a duplicate, I could not seem to find the right keywords to find any duplicates of this feature.
Edit: This post was updated to use the preferred syntax proposal mentioned at #12936 (comment), which encompasses using a simpler syntax with a generic type to enable usage in expressions.
The text was updated successfully, but these errors were encountered: