Skip to content

Question: Handling of optional properties. #13

@akolarski

Description

@akolarski

Hey, I love your library !
I read your article and I've been searching for such tool for years!

I have a question though.
Do you have any advice on how to handle optional properties ?
Here is example, lets say I have an interface representing task:

interface Task {
    name: string; // required
    estimate?: number // optional
}

and I'm creating a Type Guard:

const isTask = createTypeGuard<Task>((task) => {
  if (typeof task === "object" && task !== null && hasProperties(task, "name")) {
    const { name } = task;

    if (typeof name === "string") {
      return { name };
    }
  }
  return null;
});

This seems to works (TypeScript does not complain), but I can pass wrong type of estimate like and isTask will be wrong too :

const myTask = {name: "Example task", estimate: true}; // note that estimate is number not boolean
isTask(myTask) // true

I've modified my Type Guard to include the optional parameter estimate like so:

const isTask = createTypeGuard<Task>((task) => {
  if (typeof task === "object" && task !== null && hasProperties(task, "name", "estimate")) { // 1. added it here
    const { name } = task;

    if (typeof name === "string" && (typeof estimate === "undefined" || typeof estimate === "string") { // 2. checked type or undefined
      return { name, estimate };
    }
  }
  return null;
});

This works great, and handles the optional parameters perfectly. The previous example now returns false.

const myTask = {name: "Example task", estimate: true}; // note that estimate is number not boolean
isTask(myTask) // false

The only downside is that I still need to manually manage the optional properties here:

hasProperties(task, "name", "estimate")

If I add new optional parameter to Task - typescript will not report any issues.

Do you have any advice and if it possible at all to on how to handle optional properties more automatically ?

Best regards,
Alex

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions