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.
What did I make a mistake?
Pick
utility type is used to "filter" keys of the object type, so if you say
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
. But that means location
is a property in this object and in order to access it you need to say location.location
.
Looking at your use case, I think you want to get type of location
property and not filtered object. 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.
Location contains location
const exec = async (location: Pick<Post, 'location'>) => {
const { coordinates: [x, y] } = location.location;
}
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.