繁体   English   中英

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

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

我想使用模型中定义的接口作为函数的参数。

// 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'>'
}

我已经通过 Pick 指定了一个类型,我已经导入它以将接口用作函数参数,但我实际上无法在函数内部找到名为“坐标”的属性。

我做错了什么?

Pick实用程序类型用于“过滤”对象类型的键,所以如果你说

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

如您所见,我们的对象类型仅具有选择的属性,在您的示例中,我们选择了一个location 但这意味着location是此对象中的一个属性,为了访问它,您需要说location.location


查看您的用例,我认为您想获取location属性的类型而不是过滤对象。 获取属性类型可以通过索引类型来完成。 考虑:

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

Post['location']采用Post类型的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