Consider this type:
type T = {
b {
firstName
}
c {
firstName
d
}
}
If I wish to pick the firstName property _only_ from type b ,and also pick type d from c, I thought I would use O.P.Pick as follows:
O.P.Pick<
T,
['b' | 'c |, 'firstName','d']
however firstName in c is also selected. Should i be using a different method?
Or perhaps I need to union together branches, e.g.
O.P.Pick<
T,
['b' |, 'firstName',]
&O.P.Pick<
T,
['c' |, 'd']
This would rather verbose however.
You will need to use an intersection
type T = {
b: {
firstName: 0
d: 1
}
c: {
firstName: 2
d: 3
}
}
type pick1 = O.P.Pick<T, ['b', 'firstName']>
type pick2 = O.P.Pick<T, ['c', 'd']>
type picked = pick1 & pick2
@pirix-gh So do I understand this correctly? I have a Post, with an author property type of User.
interface Post {
title: string;
author: User;
id: number;
}
interface User {
id: number;
name: string;
uselessProperties: string;
}
I only want the User's name without his id for the GridViewPost. As I understand this is how it's supposed to be done:
type pick1 = O.P.Pick<Post, ['title' | 'id']>
type pick2 = O.P.Pick<Post, ['author', 'name']>
type GridViewPost = pick1 & pick2
My questions are: 1. Do I understand correctly? 2. Could this be somehow simplified into a single line, with a new feature or a TypeScript declare function of some sort? It looks kind of ugly.
Ideally it would be awesome to be able to do this:
type GridViewPost = O.P.Pick<Post, ['title' | 'id' | 'author', ['name'] | 'otherPropertiesOnPost'>
I have no clue if this is syntactically correct, but my idea is to make it possible to namespace the name just to the author field.
@JakubKoralewski it's the right way to do it, if your intent is to ONLY have the 'name' of the user. Otherwise you could Omit the id and keep the rest of the props.
No there are no "pretty" ways to do this, sorry. But there is a way to simplify it, but that might not work in all cases. O.P.Pick stops traversing as soon as a property isn't an object candidate. So this will work:
type pick1 = O.P.Pick<Post, ['title' | 'id' | 'author', 'name']>
(And if the & intersection was the problem, remember that you can use Compute).