[英]TypeScript not enforcing return type using Pick
Is this an intended behavior of Pick?这是 Pick 的预期行为吗? Because I suppose TypeScript would prompt an error when a different object type is returned.
因为我认为 TypeScript 在返回不同的对象类型时会提示错误。
The expected return type is { title: string }
but a type of { title: string; completed: boolean }
预期的返回类型是
{ title: string }
但类型是{ title: string; completed: boolean }
{ title: string; completed: boolean }
is returned instead. { title: string; completed: boolean }
被返回。
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.由于
duck
是Bird
一个实例,同时也是Animal
一个实例,所以这是可以接受的。 Using Pick
in this manner is another way to achieve polymorphism.以这种方式使用
Pick
是实现多态的另一种方式。
Maybe this proposal is what you're looking for.也许这个建议就是你要找的。 It looks like a lot of people want the same thing.
看起来很多人都想要同样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.