简体   繁体   English

在 Typescript 中解构赋值和“选择”时,类型上不存在属性

[英]Property does not exists on type when destructuring assignment and 'Pick' in Typescript

I want to use the interface defined in the model as the argument of a function.我想使用模型中定义的接口作为函数的参数。

// model/interface.ts
import { Document } from 'mongoose';

export interface Post extends Document {
  location: {
    type: string;
    coordinates: number[];
  };
};

// service/post_create.ts
import { Post } from '../../model/interface/post';

const exec = async (location: Pick<Post, 'location'>) => {
  const { coordinates: [x, y] } = location;
  // -> Property 'coordinates' does not exists on type 'Pick<Post, 'location'>'
}

I've specified a type via Pick, which I've imported to use the interface as a function argument, but I can't actually find a property named "coordinates" inside the function.我已经通过 Pick 指定了一个类型,我已经导入它以将接口用作函数参数,但我实际上无法在函数内部找到名为“坐标”的属性。

What did I make a mistake?我做错了什么?

Pick utility type is used to "filter" keys of the object type, so if you say Pick实用程序类型用于“过滤”对象类型的键,所以如果你说

type X = Pick<Post, 'location'>
/*
It means:
X = {
  location: {
    type: string;
    coordinates: number[];
  };
}
*/

As you can see we have object type with picked properties only, in your example we picked one - location .如您所见,我们的对象类型仅具有选择的属性,在您的示例中,我们选择了一个location But that means location is a property in this object and in order to access it you need to say location.location .但这意味着location是此对象中的一个属性,为了访问它,您需要说location.location


Looking at your use case, I think you want to get type of location property and not filtered object.查看您的用例,我认为您想获取location属性的类型而不是过滤对象。 Getting property type can be done by indexed types .获取属性类型可以通过索引类型来完成。 Consider:考虑:

const exec = async (location: Post['location']) => {
  const { coordinates: [x, y] } = location; // works
}

Post['location'] takes type of location property of the Post type. Post['location']采用Post类型的location属性类型。

Location contains location位置包含位置

const exec = async (location: Pick<Post, 'location'>) => {
  const { coordinates: [x, y] } = location.location;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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