简体   繁体   中英

TypeScript not enforcing return type using Pick

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 } { 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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM