I have one Interface:

interface MyInterface {
name: string,
email?: string,
age?: number
}

Convert fields in the interface to required


The desired result is as follows:

interface NewInterface01 {
name: string,
email: string,
age: number
}

Solution:

// Use -? for required
type ConvertFromOptionalToRequired<T extends {}> = {
    [K in keyof T]-?: T;
};
// Convert:
interface NewInterface01
    extends ConvertFromOptionalToRequired<MyInterface> {}

Convert fields in the interface to optional


The desired result is as follows:

interface NewInterface02 {
name?: string,
email?: string,
age?: number
}

Solution:

// Use ? for optional
type ConvertFromRequiredToOptional<T extends {}> = {
    [K in keyof T]?: T;
};
// Convert:
interface NewInterface02
    extends ConvertFromOptionalToRequired<MyInterface> {}

Convert some fields by name instead of all

The desired result is as follows:

type NewInterface02ChangedSomeField {
name?: string,
email: string,
age: number
}

Solution:

// Convert:
type NewInterface02ChangedSomeField = Partial<Pick<Test, 'name'>> & Required<Pick<Test, 'email' | "age">>;

Convert fields in the interface to other value type

Convert all fields

The desired result is as follows:

interface NewInterface03 {
name?: boolean,
email?: boolean,
age?: boolean
}

Solution:

// Use TTO as new Type
type ModifyAllProp<T extends {}, TTo> = {
    [K in keyof T]: TTo;
};
// Convert:
interface NewInterface03
    extends ModifyAllProp<MyInterface, boolean> {}

Convert fields according to the original value type

The desired result is as follows:

interface NewInterface04 {
name: boolean,
email: boolean
age?: number
}

Solution:

type ModifyPropByType<T extends {}, TFrom, TTo> = {
    [K in keyof T]: Exclude<T[K], undefined> extends TFrom
    ? TTo
    : Exclude<T[K], undefined> extends {}
    ? ModifyProp<T[K], TFrom, TTo>
    : T[K];
};
// Change all string field to boolean field
interface NewInterface04
    extends ModifyPropByType<MyInterface, string, boolean> {}

Convert fields in the interface to optional and change the value type


The desired result is as follows:

interface NewInterface05
{
name?: 0 | 1,
email?: 0 | 1,
age?: 0| 1
}
// Use ? for optional, and TTO or some thing for this key as a type. In this example, I use 0|1, you can try boolean or something else
type ConvertAllPropOptional<T extends {}, TTo> = {
    [K in keyof T]?: T;
};
// Convert:
interface NewInterface05
    extends ConvertAllPropOptional<MyInterface , 0 | 1> {}

,

DMCA.com Protection Status


Leave a Reply

Your email address will not be published. Required fields are marked *