I'm very new to TypeScript and what I want is declare a type for array object just like below.
const temp = [{
id: 0, // number
follower_id: 0, // number
followee_id: 0, // number
created_at: '', // string
delete_at: '', // string
}, {
id: 1,
follower_id: 1,
followee_id: 0,
created_at: '',
delete_at: '',
}];
I can make a new type for the temp array but I just wanna reuse the type that I defined before so that I can avoid repeating meaningless typing. So, here are the types that I made. Two interface for the userStateType.
interface IUserInfo {
id: number;
created_at: string;
deleted_at: string | null;
username: string;
description: string;
image_url: string;
name: string;
updated_at: string;
}
interface IFollows {
follower_id: number,
followee_id: number
}
and I tried to write down my UserStateType like below.
type UserStateType = {
userInfo: IUserInfo | null
followers: Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows | null
};
But followers in UserStateType has to be an array type not an object type so type error occurs. (Currently, I'm using this type to avoid type error. followers: [] | null
)
I can't even use []
because I used not only Pick
keyword but &
over there.
In this situation, how do I come up with efficient solution?
If my explanation is not clear enough, please comment!
CodePudding user response:
You're very close. You just need to make it an array:
followers: (Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows)[] | null
Or you could make a Follower
type and use that:
type Follower = Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows;
type UserStateType = {
userInfo: IUserInfo | null;
followers: Follower[] | null;
};
CodePudding user response:
You're just missing brackets:
interface IUserInfo {
id: number;
created_at: string;
deleted_at: string | null;
username: string;
description: string;
image_url: string;
name: string;
updated_at: string;
}
interface IFollows {
follower_id: number,
followee_id: number
}
type UserStateType = {
userInfo: IUserInfo | null
followers: (Pick<IUserInfo, 'created_at' | 'deleted_at'> & IFollows)[]
};
and then you can do:
const example:UserStateType = { followers:{created_at:'',deleted_at:'',followee_id:0,follower_id:0}], userInfo:null}