Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Pick - pick property fields

Tags:

typescript

Say I have an interface such as:

interface MyInterface {
   myProperty: {
     one: number
     two: string
   }
}

How can I Pick myProperty fields? Is this possible?
The desired result should be:

{
   one: number
   two: string
}

So that when using the type:

type MyType = ...

const t: MyType = ...
t.one = ...
like image 599
LppEdd Avatar asked Jun 07 '26 22:06

LppEdd


2 Answers

You just need to use a type query if you want to get the type of the member :

interface MyInterface {
    myProperty: {
        one: number
        two: string
    }
}

type MyType = MyInterface['myProperty']

const t: MyType = {
    one: 1,
    two: '2'
};
t.one = 3

Although refactoring to a separate type as suggested by another answer may be the saner way to go if possible.

like image 133
Titian Cernicova-Dragomir Avatar answered Jun 10 '26 18:06

Titian Cernicova-Dragomir


You can create a separate interface for myProperty:

interface MyProperty {
   one: number
   two: string
}

interface MyInterface {
   myProperty: MyProperty
}

const myObject: MyProperty = { one: 1, two: "2" };

And then use it throughout your code.

like image 35
silicakes Avatar answered Jun 10 '26 18:06

silicakes