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
Non‑void
returning assertion functions
#40562
Comments
duplicate of or related to #34636 |
Note that the duplicate #34636 (which got here first) has 39 👍 at the time of writing, and this one has only 9 👍. If these are used for prioritization, perhaps this one should be closed and the other should be reopened? |
Here's a simpler example that doesn't require any 3rd party libraries: type ValidRawData = { foo: string; };
declare function assertIsValidRawData(value: unknown): asserts value is ValidRawData;
// Ideal return type would be some like:
// ParsedData & asserts data is ValidRawData
function parseData(data: unknown) {
assertIsValidRawData(
data !== null &&
typeof data === "object" &&
Object.hasOwn(data, "foo") &&
typeof data.foo === "string"
);
...
}
const rawData: unknown = {};
const data = parseData(rawData);
const foo = rawData.foo; // <== Not currently valid. `parseData` called above should be able to assert that rawData is of type ValidRawData. |
One footgun this avoids is it can avoid unused variables: const val = api.value
ensureExists(val)
// if you never use val for rest of file, but linter is happy const val = ensureExists(api.value)
// if you never use val for rest of file, linter will complain / editor will show unused |
@natew If you never use ensureExists(api.value) |
void
returning assertion functions
You miss the whole point of the post...
This can happen if you use val for something valid, then clean up some code below it that removes all the references to it, for example. You miss seeing its not necessary anymore because it tricks the linter. Whereas the assign pattern if I remove all references below I’ll clearly see it’s dangling.
… On May 20, 2022, at 11:25 AM, Rebecca Stevens ***@***.***> wrote:
@natew If you never use val, why define it? just call the function.
ensureExists(api.value)
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.
|
Search Terms
Suggestion
A way to type a function that is both an assertion function and returning a value that is not void.
Use Cases
This is necessary to correctly type Jest’s
expect(…)
matchers, which have a generic return type ofR
.Examples
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: