Closed
Description
Search Terms
Suggestion
In Node.js, there's some methods like fs.readFile
that passes 2 parameters to callback function: (err: Error | null, data: Buffer | null) => void
. If err
is null
then data
is not null
and vice versa. It would be extremely useful if we have some sort of discriminated parameters.
Use Cases
Examples
As a callback
// Callback function type which takes two sets of parameters
interface Callback<X, E = Error> {
(error: E): void
(error: null, data: X): void
}
interface Buffer {}
declare function readFile(
filename: string,
callback: Callback<Buffer>
): void
// What I want to be able to do
readFile(
'file.txt',
(error, data) => { // TypeScript figures out parameters' type
if (error === null) {
const err: null = error
} else {
const err: Error = error
const buf: Buffer = data
}
}
)
As a function expression
interface Fn<A, B> {
(type: 'a', value: A): void
(type: 'b', value: B): void
}
const fn: Fn<string, number> = (type, value) => {
const T: 'a' | 'b' = type
const X: string | number = value
// TypeScript deduces types of `foo` and `bar` in each branch
if (type === 'a') {
const foo: 'a' = type
const bar: string = value
} else {
const foo: 'b' = type
const bar: number = value
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript codeThis wouldn't change the runtime behavior of existing JavaScript codeThis could be implemented without emitting different JS based on the types of the expressionsThis isn't a runtime feature (e.g. new expression-level syntax)
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
MartinJohns commentedon May 16, 2018
Isn't this already solved with function overloading?
KSXGitHub commentedon May 16, 2018
@MartinJohns Please focus on
// What I want to be able to do
. The point is, I want TypeScript to be able to figure out type ofdata
based on type/value oferror
.KSXGitHub commentedon May 16, 2018
Speaking of function overloading, TypeScript cannot deduce type of one parameter base on another parameter.
mhegazy commentedon May 16, 2018
Looks like a duplicate/similar use case of #24085
typescript-bot commentedon Jun 2, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.