Title: Require all user-defined guards to accept type 'any' · Issue #4898 · microsoft/TypeScript · GitHub
Open Graph Title: Require all user-defined guards to accept type 'any' · Issue #4898 · microsoft/TypeScript
X Title: Require all user-defined guards to accept type 'any' · Issue #4898 · microsoft/TypeScript
Description: If a guard accepts an input type other than any, it cannot be assured to provide any meaningful or reliable result: interface A { func1: () => number; } interface B extends A { func2: () => string; } function isB(x: A): x is B { return x...
Open Graph Description: If a guard accepts an input type other than any, it cannot be assured to provide any meaningful or reliable result: interface A { func1: () => number; } interface B extends A { func2: () => string;...
X Description: If a guard accepts an input type other than any, it cannot be assured to provide any meaningful or reliable result: interface A { func1: () => number; } interface B extends A { func2: () => s...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/4898
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Require all user-defined guards to accept type 'any'","articleBody":"If a guard accepts an input type other than `any`, it cannot be assured to provide any meaningful or reliable result:\n\n``` ts\ninterface A { \n func1: () => number;\n}\n\ninterface B extends A {\n func2: () => string;\n}\n\nfunction isB(x: A): x is B {\n return x != null && typeof x.func2 === \"function\";\n}\n\nfunction example(input: A) {\n if (isB(input)) {\n input.func2(); // Guaranteed to work!\n input.func1(); // Can fail :(\n }\n}\n```\n\nThe problem is that the guard `isB` _assumed_ `input` had type `A`, but that assumption is not generally safe to make, especially when the function was called by a plain Javascript consumer, who does not have a compile-time checking mechanism for the associated static type. To fix this, we need to define an additional guard for `A`, that would accept input type `any`.\n\n``` ts\nfunction isA(x: any): x is A {\n return x != null && typeof x === \"object\" && typeof x.func1 === \"function\";\n}\n```\n\nand then combine it with the check for `isB`:\n\n``` ts\nfunction example(input: A) {\n if (isA(input) && isB(input)) {\n input.func2(); // Guaranteed to work!\n input.func1(); // Guaranteed to work!\n }\n}\n```\n\nBut now `isB` is _dependent_ on a prior call to `isA` to provide a correct result, meaning it still isn't reliable or useful by itself. However, we can fix this by having `isB` internally call `isA`, and now its input type can also be safely changed to `any`:\n\n``` ts\nfunction isB(x: any): x is B {\n return isA(x) && typeof x.func2 === \"function\";\n}\n```\n\nThis transformation can be done with any user-defined guard that accepts a type other than `any` and removes the need for these types of guards in general.\n## Class embedded guards\n\nGuards that are embedded in classes:\n\n``` ts\nclass A {\n ...\n\n isB(): this is B {\n return false;\n }\n}\n\nclass B extends A {\n ...\n\n isB(): this is B {\n return true;\n }\n}\n\nclass C extends B {\n ...\n\n isB(): this is B {\n return false;\n }\n}\n```\n\nAre even less reliable:\n\n``` ts\nfunction example(input: A) {\n if (input.isB()) { \n ...\n }\n}\n\nexample(undefined); // Error, 'input' is 'undefined'\nexample(callSomeUnsafeFunction()); // Error, 'isB' method is not found\n```\n\nand would always need to be composed with a check for the base type (which should hopefully also include a check for `null` or `undefined` inputs):\n\n``` ts\nfunction example(x: A) {\n if (isA(x) && x.isB()) {\n ...\n }\n}\n```\n\nTo fix this, we'll create a function that combines all the tests for `B` and accepts type `any`:\n\n``` ts\n// This guard would only return true if the input is a strict instance of 'B',\n// and not one of the derived classes.\nfunction isStrictlyB(x: any): x is B {\n return x != null && isA(x) && isB(x) && !isC(X);\n}\n```\n\nThis removes the need for these types of guards as well.\n## Implications\n- All user-defined guards can now assumed to be sound at _run-time_ when called at any position and context and to correctly handle `null` and `undefined` input values.\n- All user-defined guards can now be safely applied on function arguments, including when the function is called by plain Javascript consumers.\n- All user-defined guards can be safely used with automated run-time type checkers without needing to apply complex search algorithms in attempt to assemble logically sound compositions based on multiple guards.\n- Programmers are encouraged to apply healthy and sound practices when writing run-time checks.\n- Type-safety is improved in general.\n## Conclusion\n\nGuards that apply compile-time assumptions on their input value's type are not generally reliable for use by themselves, may yield incorrect results or throw an exception. There are safer and more reusable alternatives for these types of guards, thus they can be deprecated without a significant loss of functionality.\n","author":{"url":"https://github.com/rotemdan","@type":"Person","name":"rotemdan"},"datePublished":"2015-09-21T14:38:48Z","url":"https://github.com/microsoft/TypeScript/issues/4898"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:6e487b04-85fe-895f-3ea5-d3c8a31ed309 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A676:363D8E:2BAA33:398071:6B00C175 |
| html-safe-nonce | 5d0e452627cc91678d2220dc761ff4fb945a2f2b871eeb0cc9b1a42251e11d40 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNjc2OjM2M0Q4RToyQkFBMzM6Mzk4MDcxOjZCMDBDMTc1IiwidmlzaXRvcl9pZCI6IjE1OTQ5NDc5NTY5Nzk1ODEzMDEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | cc9db9acb37bb8b75756be0762cb412326d490661e624bb865c3abf0cad77df0 |
| hovercard-subject-tag | issue:107527074 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/4898/issue_layout |
| twitter:image | https://opengraph.githubassets.com/3c772a22c0b34e797f86ed22f99d144607059a6fa254bad0088e0f81eb8ac0ad/microsoft/TypeScript/issues/4898 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/3c772a22c0b34e797f86ed22f99d144607059a6fa254bad0088e0f81eb8ac0ad/microsoft/TypeScript/issues/4898 |
| og:image:alt | If a guard accepts an input type other than any, it cannot be assured to provide any meaningful or reliable result: interface A { func1: () => number; } interface B extends A { func2: () => string;... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | rotemdan |
| hostname | github.com |
| expected-hostname | github.com |
| None | 93edd3bebc4afb7ce711ee74cb5d2a95927850b082a4d43e212222389cb1c415 |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 1fee81a280ea86312b69448e261b418189bfd5b5 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width