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

[Feature request] Union type operator that prefer narrow types over wide ones #46548

Open
5 tasks done
owl-from-hogvarts opened this issue Oct 27, 2021 · 5 comments
Open
5 tasks done
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript

Comments

@owl-from-hogvarts
Copy link

owl-from-hogvarts commented Oct 27, 2021

Suggestion

πŸ” Search Terms

narrow, types, type, wide. narrowing

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

When | type operator is used to alternate types sometimes it is useful alternate its behaviour i.e. prefer more narrow type than more wide (to better understand look at example below). Something like const but not so strict. This type of behaviour will require to implement handilg for both sides of expression.

πŸ“ƒ Motivating Example

This feature will help to better reflect dependency of one field on another (when both field are optional, but if one specified, other should be too).

πŸ’» Use Cases

Lets imagine (btw it is real world example) that we want autoconfigure navbar according to config of web app router. So when navTitle property is there and containg a string we are intrested in that element i.e. it will be placed on navbar with lable contained in navTitle property. And it shoud lead to somewhere, right? But to where? To figure it out we should know path. Thus navTitile property is dependent on path (which is optional by default in angular). OK! That is not a difficult issue:

type Router = {path?: string, data?: any}

type RouterWithNavTitile = (RequiredProps<Router, "path"> & {navTitle: string})
type CustomRouterConfig = Router | RouterWithNavTitile
export type RequiredProps<T, P extends keyof T> = Omit<T, P> & Pick<Required<T>, P>

const test1: RouterWithNavTitile = {navTitle: "asd"} 

const test: CustomRouterConfig[] = [
  // all works as expected
  {path: "asd"},
  {navTitle:"asd", path:"asd"},
  // here is error. yeap. when navTitle present, path should be too but it is not here
  {navTitle:"asd"},
  {foo: "asd"}
]

Solution looks pretty good. Unless you are figurring out, that we should place all additional data into data property (this is angular way). Lets try:

type RouteWithNavTitle = RequiredProps<Route, "path"> & {data: {navTitle: string}}
type RouteWithOptionalNavTitle = Route | RouteWithNavTitle

const test: RouteWithOptionalNavTitle[] = [
  // woops! No error! Path is required and not present! And no error
  {
    data: {
        navTitle: 'asd'
    }
  }
]

Why? That why! Route | RouteWithNavTitle will always resolve to Route since RouteWithNavTitle is narrowed Route (remeber data property? in route it is any but in RouteWithNavTitle it is narrowed to {navTitile: string}). Typescript will always prefer wider types for compatibility reasons. It is not always convinent as in considired example.

You may argue: "there is an const expressions". Yes. But they are too strict.

To solve the preoblem i suggest |& operator which is more like regular | but will prefer narrow types when possible (when shape of object satisfy narrowed variant i.e. it can be assigned to more narrow variant). It will require to implement handling of both sides of expression (in this example for Route and RouteWithNavTitle).

P.S. Thank you very much for reading this. Leave your comments for me to understand if i missed something or explained wrong.

@sandersn sandersn added Suggestion An idea for TypeScript Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. labels Nov 10, 2021
@sandersn
Copy link
Member

I'm confused about the problem with the angular-style example, though. As far as I can tell, the only reason that the error goes unnoticed is that both Router and RouterWithNavTitle have a property named data and Router's data: any. If you change the name or give a real type to Router.data the problem goes away.

I guess that |& is intended to solve this problem, but you need to add an explanation of how it handles any, which isn't, strictly speaking a 'narrow' or 'wide' type -- more of a type that disables type checking.

@sandersn sandersn changed the title [Feature request] Prefer narrow types than wide [Feature request] Union type operator that prefer narrow types over wide ones Nov 10, 2021
@owl-from-hogvarts
Copy link
Author

owl-from-hogvarts commented Apr 7, 2022

@sandersn

If you change the name or give a real type to Router.data the problem goes away.

I can't do either of these.

Any actually is the widest type because we can assing any value to it.

Handling Any

Lets consider two situatuins: assign and use.

Assign:

Assignation should be handled by typescript as follows:

  1. Assume that value belongs to more wide type
  2. Figure out which type is more narrow (RouteWithNavTitle in our case)
  3. Compute the difference between narrow and wide type and provide list of fields, types of which differs (path, data)
  4. Select these fields from value and try to assign to more narrow type (with only these fields left:
    Pick<RouteWithNavTitle, 'path'|'data'>)
  5. If at least one field is assignable (i.e. hits), and there is at least one required field that is not present, we consider value as more narrow type (thus producing errors if present)

Note: type of missing fields is unknown
Example 1 (data field provided and hits, path is missing; same would be for data with optional navTitle):

type RouteWithNavTitle = RequiredProps<Route, "path"> & {data: {navTitle: string}}
type RouteWithOptionalNavTitle = Route |& RouteWithNavTitle

const test: RouteWithOptionalNavTitle[] = [
// at first, `test` considered as Route
// Then difference between Route and RouteWithNavTitle is computed. 
// Fields, type of which differs, are: `path`, `data`.
// Selecting `path` ('cause missing, type is `unknown`) and `data` field of `test` variable and trying to assign to 
// Pick<RouteWithNavTitle, "path"|"data">
// `data` property hits. `path` is **not** optional. Now consider `test` as `RouteWithNavTitle `
// Produce error about no `path` field present
  {
    data: {
        navTitle: 'asd'
    }
  }
]

Example 2 (data field provided but misses):

type RouteWithNavTitle = RequiredProps<Route, "path"> & {data: {navTitle: string}}
type RouteWithOptionalNavTitle = Route |& RouteWithNavTitle

const test: RouteWithOptionalNavTitle[] = [
// at first, `test` considered as Route
// Then difference between Route and RouteWithNavTitle is computed. 
// Fields, type of which differs, are: `path`, `data`.
// Selecting `path` and `data` field of `test` variable and trying to assign to 
// Pick<RouteWithNavTitle, "path"|"data">
// `data` property misses. 
// No hits at all, so it is defently not a RouteWithNavTitle 
  {
    data: {
        foobar: 'asd'
    }
  }
]

Note: if required field is missing, produce error; if optional field is missing, consider as wider type if assignable
Example 3 (path required and provided, data is optional and missing):

type RouteWithNavTitle = RequiredProps<Route, "path"> & {data?: {navTitle: string}}
type RouteWithOptionalNavTitle = Route |& RouteWithNavTitle

const test: RouteWithOptionalNavTitle[] = [
// at first, `test` considered as Route
// Then difference between Route and RouteWithNavTitle is computed. 
// Fields, type of which differs, are: `path`, `data`.
// Selecting `path` and `data` (`data` is `unknown` bacause not present) 
// field of `test` variable and trying to assign to 
// Pick<RouteWithNavTitle, "path"|"data">
// `path` property hits. But `data` misses
// So consider `test` as Route, because `data` is optional
  {
    path: "foobar"
  }
]

Use:

Inside function assume that routerConfig is Route, unless accessing differencing fields. To access these fields developers must provide type guard for them (and typescript should force them to do so)

type RouteWithNavTitle = RequiredProps<Route, "path"> & {data: {navTitle: string}}
type RouteWithOptionalNavTitle = Route |& RouteWithNavTitle

functions foobar(routerConfig: RouteWithOptionalNavTitle ) {
  // Error: path is optional in `Route`
  routerConfig.path;
  // Error: Provided only in RouteWithNavTitle. Please, use type guard to check if property is present
  routerConfig.data.navTitle;

 // unambiguously resolves to RouteWithNavTitle
 if (routerConfig.data.navTitle) {
    // its ok. Inside this branch assumes that `routerConfig` is `RouteWithNavTitle`
    routerConfig.data.navTitle;
    routerConfig.path;
  }

  // ambiguously roslves to Route and RouteWithNavTitle so prefer Route (wider type)
  if (routerConfig.path) {
    routerConfig.path; // ok
    routerConfig.data.navTitle // Error: not Present in Route type
  }


}

@owl-from-hogvarts
Copy link
Author

Why is "|&" rather than any other symbol? Thats because on provider side (i.e. variable declaration) this behaves like "&" or more close to function overloads sorted from most narrow to most wide (tryes to assign to more narrow type, if fails, go to the next more wide one, Just like for function overloads). While on consumer side more like "|" forcing to implement runtime typecheck in favor of some side of this composit type

@owl-from-hogvarts
Copy link
Author

Hm, It seems I have found analogue to this feature in zig-lang. It is called tagged union. Works like enum with set of additional fields which depends on current enum value.

Ref: https://ziglang.org/documentation/master/#Tagged-union

@owl-from-hogvarts
Copy link
Author

Use case which I have mentioned above highlights, that tagged unions are useful to provide typesafe configuration and express dependency of one field over another

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 Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants