TypeScript not enforcing return type using Pick

Viewed 64

Is this an intended behavior of Pick? Because I suppose TypeScript would prompt an error when a different object type is returned.

The expected return type is { title: string } but a type of { title: string; completed: boolean } is returned instead.

Playground

interface Todo {
  title: string
  description: string
  completed: boolean
}

// Pick "title" and "completed" from Todo
type TodoPreview = Pick<Todo, "title" | "completed">

// Creating a TodoPreview object
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
}
  
const mytodo = (): Pick<Todo, "title"> => {
    return todo // No error returning a TodoPreview
}
1 Answers

What you're doing is basically the same as this:

interface Animal {
   color?: string;
}

interface Bird extends Animal {
   canFly: boolean
}

function getAnimalColor(animal: Animal): Animal | undefined {
   return animal.color ? animal : undefined;
}

const duck: Bird = {
   color: 'brown',
   canFly: true
}

const animalColor = getAnimalColor(duck);

console.log(animalColor)

Since duck is an instance of Bird which is also an instance of Animal, this is acceptable. Using Pick in this manner is another way to achieve polymorphism.

Maybe this proposal is what you're looking for. It looks like a lot of people want the same thing.

Related