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

Exact Types #12936

Open
blakeembrey opened this issue Dec 15, 2016 · 286 comments
Open

Exact Types #12936

blakeembrey opened this issue Dec 15, 2016 · 286 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@blakeembrey
Copy link
Contributor

blakeembrey commented Dec 15, 2016

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.

interface User {
  username: string
  email: string
}

const user1: User = { username: 'x', email: 'y', foo: 'z' } //=> Currently errors when `foo` is unknown.
const user2: Exact<User> = { username: 'x', email: 'y', foo: 'z' } //=> Still errors with `foo` unknown.

// Primary use-case is when you're creating a new type from expressions and you'd like the
// language to support you in ensuring no new properties are accidentally being added.
// Especially useful when the assigned together types may come from other parts of the application 
// and the result may be stored somewhere where extra fields are not useful.

const user3: User = Object.assign({ username: 'x' }, { email: 'y', foo: 'z' }) //=> Does not currently error.
const user4: Exact<User> = Object.assign({ username: 'x' }, { email: 'y', foo: 'z' }) //=> Will error as `foo` is unknown.

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.

type Foo = Exact<X> | Exact<Y>

type Bar = Exact<{ username: string }>

function insertIntoDb (user: Exact<User>) {}

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.

@HerringtonDarkholme
Copy link
Contributor

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 type A = number | B, thanks to automatic semicolon insertion.

I think this might not I expect if exact type is introduced.

@normalser
Copy link

Not sure if realted but FYI #7481

@DanielRosenwasser
Copy link
Member

DanielRosenwasser commented Dec 15, 2016

If the {| ... |} syntax was adopted, we could build on mapped types so that you could write

type Exact<T> = {|
    [P in keyof T]: P[T]
|}

and then you could write Exact<User>.

@DanielRosenwasser DanielRosenwasser added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Dec 15, 2016
@joshaber
Copy link
Member

This is probably the last thing I miss from Flow, compared to TypeScript.

The Object.assign example is especially good. I understand why TypeScript behaves the way it does today, but most of the time I'd rather have the exact type.

@blakeembrey
Copy link
Contributor Author

@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 😄

@rotemdan
Copy link

rotemdan commented Dec 17, 2016

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: Type3, Type5)

@blakeembrey
Copy link
Contributor Author

blakeembrey commented Dec 17, 2016

@rotemdan See the above answer, there's the generic type Extact instead which is a more solid proposal than mine. I think this is the preferred approach.

@rotemdan
Copy link

rotemdan commented Dec 17, 2016

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 only. I had a draft for a proposal for this several months ago, I think, but I never submitted it:

function test(a: only string, b: only User) {};

That was the best syntax I could find back then.

Edit: just might also work?

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)

@rotemdan
Copy link

rotemdan commented Dec 19, 2016

I was wondering, maybe both keywords could be introduced to describe two slightly different types of matching:

  • just T (meaning: "exactly T") for exact structural matching, as described here.
  • only T (meaning: "uniquely T") for nominal 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 only seems appropriate to them. I'm only suggesting this as an option.

(Edit: just a note about only when used with classes: there's an ambiguity here on whether it would allow for nominal subclasses when a base class is referenced - that needs to be discussed separately, I guess. To a lesser degree - the same could be considered for interfaces - though I don't currently feel it would be that useful)

@ethanresnick
Copy link
Contributor

This seems sort of like subtraction types in disguise. These issues might be relevant: #4183 #7993

@blakeembrey
Copy link
Contributor Author

@ethanresnick Why do you believe that?

@johnnyreilly
Copy link

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 😉)

@mohsen1
Copy link
Contributor

mohsen1 commented Feb 17, 2017

I don't like the pipe syntax inspired by Flow. Something like exact keyword behind interfaces would be easier to read.

exact interface Foo {}

@blakeembrey
Copy link
Contributor Author

@mohsen1 I'm sure most people would use the Exact generic type in expression positions, so it shouldn't matter too much. However, I'd be concerned with a proposal like that as you might be prematurely overloading the left of the interface keyword which has previously been reserved for only exports (being consistent with JavaScript values - e.g. export const foo = {}). It also indicates that maybe that keyword is available for types too (e.g. exact type Foo = {} and now it'll be export exact interface Foo {}).

@mohsen1
Copy link
Contributor

mohsen1 commented Feb 19, 2017

With {| |} syntax how would extends work? will interface Bar extends Foo {| |} be exact if Foo is not exact?

I think exact keyword makes it easy to tell if an interface is exact. It can (should?) work for type too.

interface Foo {}
type Bar = exact Foo

@basarat
Copy link
Contributor

basarat commented Feb 19, 2017

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 🌹

@blakeembrey
Copy link
Contributor Author

blakeembrey commented Feb 19, 2017

@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 Foo is exact or not.

The usage of an exact keyword seems ambiguous - you're saying it can be used like exact interface Foo {} or type Foo = exact {}? What does exact Foo | Bar mean? Using the generic approach and working with existing patterns means there's no re-invention or learning required. It's just interface Foo {||} (this is the only new thing here), then type Foo = Exact<{}> and Exact<Foo> | Bar.

@RyanCavanaugh
Copy link
Member

We talked about this for quite a while. I'll try to summarize the discussion.

Excess Property Checking

Exact 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 types

Related 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
unknown properties (almost all of them). And at the other end you have functions which generically operate over all properties (e.g. Object.keys).

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. Point2D / Point3D is a good example - you might reasonably say that a magnitude function should have the type (p: exact Point2D) => number to prevent passing a Point3D. But why can't I pass my { x: 3, y: 14, units: 'meters' } object to that function? This is where EPC comes in - you want to detect that "extra" units property in locations where it's definitely discarded, but not actually block calls that involve aliasing.

Violations of Assumptions / Instantiation Problems

We have some basic tenets that exact types would invalidate. For example, it's assumed that a type T & U is always assignable to T, but this fails if T is an exact type. This is problematic because you might have some generic function that uses this T & U -> T principle, but invoke the function with T instantiated with an exact type. So there's no way we could make this sound (it's really not OK to error on instantiation) - not necessarily a blocker, but it's confusing to have a generic function be more permissive than a manually-instantiated version of itself!

It's also assumed that T is always assignable to T | U, but it's not obvious how to apply this rule if U is an exact type. Is { s: "hello", n: 3 } assignable to { s: string } | Exact<{ n: number }>? "Yes" seems like the wrong answer because whoever looks for n and finds it won't be happy to see s, but "No" also seems wrong because we've violated the basic T -> T | U rule.

Miscellany

What is the meaning of function f<T extends Exact<{ n: number }>(p: T) ? 😕

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 { type: "name", firstName: "bob", lastName: "bobson" } or { type: "age", years: 32 } but don't want to accept { type: "age", years: 32, firstName: 'bob" } because something unpredictable will happen. The "right" type is arguably { type: "name", firstName: string, lastName: string, age: undefined } | { type: "age", years: number, firstName: undefined, lastName: undefined } but good golly that is annoying to type out. We could potentially think about sugar for creating types like this.

Summary: Use Cases Needed

Our 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.

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature and removed In Discussion Not yet reached consensus labels Mar 7, 2017
@Exifers
Copy link

Exifers commented Sep 8, 2024

This would help to perform mutations on generics.

Currently if T[K] is a generic type, we cannot constrain it so that something like number is assignable to it.
This makes some simple functions impossible to implement with generics:

function reset<T extends Record<K, number>, K extends keyof T>(v: T, k: K) {
  v[k] = 0 // Error: requires number to be assignable to T[K], but T[K] could be arbitrarily precise
}

function increment<T extends Record<K, number>, K extends keyof T>(v: T, k: K) {
  v[k] = v[k] + 1 // Error: requires both T[K] to be assignable to number (ok) and number to be assignable to T[K]
}

Of course we could write these functions without generics for v, but this is not possible in the context of an ORM for example:

interface BaseEntity {
    id: string
}

function createOrm<Entity extends BaseEntity>() {
    return {
        reset<T extends Entity & Record<K, number>, K extends keyof T>(entity: T, key: K) {
            this.update(entity, key, 0) // Error not fixable for now
        },
        increment<T extends Entity & Record<K, number>, K extends keyof T>(entity: T, key: K) {
            this.update(entity, key, entity[key] + 1) // Error not fixable for now
        },
        update<T extends Entity, K extends keyof T>(entity: T, key: K, value: T[K]) {
            entity[key] = value

            // saves the entity here through DB request so uses entity.id
        }
    }
}

In this case we need the generics to ensure the user code will pass an Entity with an id to the update function.

Playground

If we'd have a way to specify that T[K] is exactly of type number, then it would be available for both reading and writing in the functions and they could be implemented without error.

@RobertSandiford
Copy link

RobertSandiford commented Sep 8, 2024

Currently if T[K] is a generic type, we cannot constrain it so that something like number is assignable to it. This makes some simple functions impossible to implement with generics:

This isn't the topic of the ticket, which is prohibiting additional properties on the value that are not present on the type.

Your issue is related to lack of invariant constraints on writable properties #18770 and somewhat also the lack of lower bound constraints #14520

(edit: edited the linked issues)

@dead-claudia

This comment has been minimized.

@jcalz

This comment has been minimized.

@robbiespeed
Copy link

@Exifers while exact types may make it easier to implement the restrictions you want in that example, I don't think it's strictly necessary. You can instead restrict the K parameter, though you need to make some (safe) assertions inside the implementation.

function createOrm<Entity extends BaseEntity>() {
    return {
        reset<T extends Entity, K extends { [P in keyof T]: 0 extends T[P] ? P : never }[keyof T]>(entity: T, key: K) {
            this.update(entity, key, 0 as T[K]);
        },
        increment<T extends Entity, K extends { [P in keyof T]: number extends T[P] ? P : never }[keyof T]>(entity: T, key: K) {
            this.update(entity, key, ((entity[key] as number) + 1) as T[K]);
        },
        update<T extends Entity, K extends keyof T>(entity: T, key: K, value: T[K]) {
            entity[key] = value
        }
    }
}

Playground

@andybarron
Copy link

this feature is my white whale 🐳

there are definitely concrete use cases for exact types. folks have already mentioned the issue of Object.keys() giving you string[]; it would be great to get (keyof T)[] when you can forbid additional properties.

i think a more compelling use case is dynamic database insertions in ORMs and query builders such as kysely. (related issues: 1, 2)

// assume the "person" table only has a "name" column.

await db.insertInto('person').values({ name: "Foo", oops: "bad" ).execute();
// tsc's excess property checks will correctly flag this error IF you use an object literal.

const invalidPerson = {
  name: "Bar",
  oops: "worse",
};

await db.insertInto('person').values(invalidPerson).execute();
// this will pass type checking but blow up at runtime :(

it's great that excess property checking can prevent some instances of this problem, but in practice, it's a very limited subset of instances.

in this example, excess property checking and structural typing are working as intended. i believe a new, opt-in language feature would be ideal for this problem (and many others mentioned in this long-running thread).

@nmn
Copy link

nmn commented Feb 24, 2025

There are many use-cases that have presented over and over again. Saying "there are no use-cases" anymore feels in bad taste at this point.

However, there is still the question of how to implement this feature in a way that doesn't have massive breaking changes.

Step 1

To start, object type spreads should be added:

type C = {...A, ...B, foo: string}

This would be similar but distinct from & as instead of "merging" objects, this would have the same semantics as object spreads. Any key types from B would override the same keys from A and so on.

When A or B are inexact object types (which is all object types today), then C should be inexact as well and should allow extra keys not explicitly included in A or B, or foo.

Step 2

New syntax for defining exact object types. There are two way this could be done:

  1. Use an Exact<{}> utility type. This would be similar to how Readonly is used today
  2. Introduce new syntax like {| foo: string, bar: number |} like Flow did.

Using & on exact object types should result in never types unless the keys of the object keys match up perfectly.

{| a: string |} & {| b: number |} === never

{| a: string | number |} & {| a: number | null |} === {| a: number |}

Step 3

Encourage moving to object type spreads instead of & in the ecosystem and ship codemod tools.

Step 4

Start migrating object types to be exact in many more cases

Step 5

Consider making object types exact by default

@nikelborm
Copy link

nikelborm commented Feb 24, 2025

Speaking of step 1, check this (ts playground) out. Some time ago I wrote a type that properly merges objects and simulates spread syntax for my @nikelborm/joiner library

@nmn
Copy link

nmn commented Feb 24, 2025

@nikelborm I know that this is already possible, but you should not have to jump through the hoops you did just to merge object types. Adding object type spread syntax is a good idea for Typescript regardless.

@ssalbdivad
Copy link

ssalbdivad commented Feb 24, 2025

@nmn The spread syntax is a great idea!

So great in fact that I actually added the same thing to ArkType 😅

Image
https://arktype.io/docs/objects#properties-spread

ArkType also implements undeclared key handling that works just like you describe when combined with spreading and intersections.

The implementation and/or unit tests might be useful as a point of reference if someone decides to add one or both of these features to TypeScript.

@andybarron
Copy link

andybarron commented Feb 24, 2025

Step 3

Encourage moving to object type spreads instead of & in the ecosystem and ship codemod tools.

Step 4

Start migrating object types to be exact in many more cases

Step 5

Consider making object types exact by default

i strongly disagree that "exact by default" is the way to go. typescript's huge ecosystem is proof that its structural typing strategy fits most use cases. exact types can be added to the language without huge ecosystem overhauls or codemods.

ultimately, exact types should be another tool in typescript's toolbelt to support specific use cases. they have trade-offs and should not be the default behavior. but i think we've listed enough such cases that there's a strong argument for adding them to the language.

given this issue's age, scope, and massive discussion thread, i am considering drafting a new, narrowly scoped feature request with concrete use cases. the FAQ explicitly lists this issue as a "common feature request," so no sense creating more noise for the team.

@sebmarkbage
Copy link

sebmarkbage commented Feb 24, 2025

I think for React we'd want to strongly encourage exact by default due to how it can catch mistakes in serialization boundaries for React Server Components. Inexact objets might pass extra arguments which then end up erroring at runtime. E.g. having a standard set of lint rules that lints against inexact.

I think the lesson learned from Flow was that it's not very useful unless it's the default because to catch mistakes like this you wouldn't know beforehand that you need to opt-in to it.

I think it doesn't necessarily have to be "the default" as much as it has to look good - aesthetically. If you have to type Exact<{...}> everywhere (due to the lint rule telling you so) there would be riots in the streets. If it was {| ... |} everywhere it would maybe be ok, but it would still make TypeScript code look quite messy. But if that's better from backwards compat perspective ok.

@RobertSandiford
Copy link

There are many use-cases that have presented over and over again. Saying "there are no use-cases" anymore feels in bad taste at this point.

However, there is still the question of how to implement this feature in a way that doesn't have massive breaking changes.

It's a bit of a nightmare waiting to happen due to exact objects not being assignable as writable inexact object arguments, and inexact objects not being assignable as exact objects. It would create a divide where you'd want to work with one of the other, or you'd need compatibility/conversion functions and the like to make things work. That's not something I would look forward to.

I've said before that readonly objects would make things easier - because both exact and inexact objects can be assigned to a readonly inexact argument, allowing libraries to provide an interface that works with both object types. Writable objects are also unsafe currenly, so this also kills an existing type unsafety as well, and likely it's compatible with much existing code due to that type unsafety with using mutable objects.

I'm confident that readonly objects (and probably with it explicitly read/write objects with stricter type safe assignability rules) is the way to go.

I wouldn't say that knowing how to implement this is the problem - but rather a question of someone or some people being willing to do the work on creating it.

@hrasoa
Copy link

hrasoa commented Feb 25, 2025

If I want my whole codebase to use exact types, adding an utility would add lot of frictions as devs can forget to use it in some places. I think it should a config that we can enable in the tsconfig, like noUncheckedIndexedAccess in instance.

@ssalbdivad
Copy link

ssalbdivad commented Feb 25, 2025

If I want my whole codebase to use exact types, adding an utility would add lot of frictions as devs can forget to use it in some places. I think it should a config that we can enable in the tsconfig, like noUncheckedIndexedAccess in instance.

@RyanCavanaugh has expressed concern in the past that developers would misuse exactness by applying it to all their APIs, leading to breaking changes downstream.

While I don't think the potential for misuse is a good reason not to implement a feature, it should be considered when determining how explicitly it is applied.

TS is structural because in most contexts, it is safe, simple, and performant to allow and ignore extra properties on an object.

Exactness can be thought of as an additional constraint on an object. It narrows the set of allowed values the same way adding a property like foo: boolean or index signature like [x: string]: number does. It could even theoretically be expressed as an index signature of [!(keyof obj)]: never.

There is a genuine issue in the community where TS devs see a config or lint rule called strictX or exactY and think they should always enable it to make their project better and safer. This may be true in some cases like strictNullChecks, but certainly not all.

Applying exactness should always be an explicit part of a type's definition to avoid this confusion and emphasize it as a context-dependent decision like making a key optional.

@nmn
Copy link

nmn commented Feb 27, 2025

i strongly disagree that "exact by default" is the way to go. typescript's huge ecosystem is proof that its structural typing strategy fits most use cases. exact types can be added to the language without huge ecosystem overhauls or codemods.

I used the word "consider" for a reason. But, side note, exact object types are just as much "structural typing" as the inexact object types that exist today. They just don't allow extra stuff.

The codemods specifically was for migrating from & to spread syntax as I think it is a lot more readable and less finicky.

It's a bit of a nightmare waiting to happen due to exact objects not being assignable as writable inexact object arguments, and inexact objects not being assignable as exact objects.

Typescript, intentionally, allows a bunch of unsafe behavior already when it comes to variance. These issues are similar and I could see the argument to allow converting between exact and inexact object types even if it is unsafe because most of Typescript is only really safe if you don't use mutation.

TS is structural because in most contexts, it is safe, simple, and performant to allow and ignore extra properties on an object.

Exact object types are structural. Exact objects are safer and prevent extra data from slipping through and causing side effects. And they are just as simple, just a different set of rules.

I see the argument about backwards compatibility and I understand the compromises needed to not break the ecosystem, but if we were to ignore all of that exact object types are the better fit in 99% of use-cases. Almost none of the code that uses Flow uses inexact object types even though it is still supported.


Another side note. IMO, asking for implicitly allowing extra keys on an object type is akin to implicitly allowing extra values in a tuple type:

const twoVals: [number, number] = [1, 2, 3, '4', true];

The value clearly satisfies the requirement of the first two elements being numbers. Why does it matter if it has extra values?

Tuples already have the features we want for object types.

  • Tuples can be spread with ... syntax
  • Tuples can allow extra elements: [number, number, ...unknown[]]
  • Tuples don't allow extra elements by default.

Would you make the argument that Tuples would be better if they were inexact by default and allowed extra keys and that it would fit most use-cases and exact tuple types are an extra feature that should be used explicitly?

@RobertSandiford
Copy link

RobertSandiford commented Feb 27, 2025

Typescript, intentionally, allows a bunch of unsafe behavior already when it comes to variance. These issues are similar and I could see the argument to allow converting between exact and inexact object types even if it is unsafe because most of Typescript is only really safe if you don't use mutation.

Converting safely can be done by extracting known keys to make an exact object, or cloning the object to make an inexact. But these are chores and runtime operations. I'm not sure how much benefit Exact types provide if you then use unsafe casts to use them, that seems like you're undoing the benefit that they provide.

All this is why I say implement readonly objects first, because an exact O can be assigned safely to readonly O, and so can an inexact O, so now we can use exact and inexact objects safely without casts or conversions, and all that it requires is that libs add a readonly modifier to their arguments and don't modify received objects, which as you say is already an unsafe op, so it achieves an additional benefit of preventing unsafe object modification.

Besides, unsafe variance has a lot to do with legacy functionality that needs to be supported (DOM methods are usually mentioned), which doesn't apply here. It's a necessity not a preference.

Another side note. IMO, asking for implicitly allowing extra keys on an object type is akin to implicitly allowing extra values in a tuple type:

const twoVals: [number, number] = [1, 2, 3, '4', true];

The value clearly satisfies the requirement of the first two elements being numbers. Why does it matter if it has extra values?

Exact tuples is a side affect of tuples have a .length property, { [1, 2, 3, '4', true], length: 5 } doesn't assign to { [number, number], length: 2 }. It is still structural at heart.

Be clear, I am not opposed to exact types. I'm opposed to creating a new divide like the CJS/ESM module divide that plagued us. That could have been handled better (synchronous require of non-top-level-await ESM modules from CJS, esModuleInterop issues, etc).

Let's not do that again. Any effort at exact types needs to be well considered and planned. But still, this needs an implementer to go forward.

@bliddicott-scottlogic
Copy link

bliddicott-scottlogic commented Feb 28, 2025

I've got a mockup of exact types, implemented entirely in the existing type system.

The real thing that is needed to make this work properly is a TypeError type, which if generated, generates a nice type error. I even have that, it's just that the errors it generates aren't nice and aren't understood by the type system compiler.

TL;DR: If there was a TypeError type which was understood by the compiler, it would be possible to build absolutely everything else in the existing type system. I know because I've done it already.

@RobertSandiford
Copy link

RobertSandiford commented Mar 1, 2025

I've got a mockup of exact types, implemented entirely in the existing type system.

The real thing that is needed to make this work properly is a TypeError type, which if generated, generates a nice type error. I even have that, it's just that the errors it generates aren't nice and aren't understood by the type system compiler.

TL;DR: If there was a TypeError type which was understood by the compiler, it would be possible to build absolutely everything else in the existing type system. I know because I've done it already.

Useful in it's own right - I presume there is a ticket for it somewhere.

Doom in the type system - a lot of things are possible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.