Trying to find a solution in TypeScript for defining a type that represents a non-zero number:
type Task = { id: number };
const task: Task = { id: 5 };
const tasks: { [taskId: number]: Task } = { 5: task };
function getTask(taskId: number | undefined): Task | undefined {
return taskId && tasks[taskId];
}
In the provided code, TypeScript raises an issue because taskId
is considered a number and may potentially be 0
, which is falsey. This could result in the function returning 0
instead of a Task
or undefined
. Realistically, it is not feasible for a task id to be 0
; it will always be a positive integer. Is there a method to define the Task
type in such a way that indicates to TypeScript that this number will never be falsey? It would be preferable to avoid adding extra conditional statements for TypeScript acknowledgment.