Home > Net >  TypeScript: Make interface fields required, but only for array types
TypeScript: Make interface fields required, but only for array types

Time:11-17

Is it possible to make all interface fields required but only array type? The Required operator makes all fields mandatory, but I only need those fields that are an array ???

`

interface IExample {
    a: number,
    b?: string,
    c?: number[]
}

function getTest(data: IExample): Required<IExample> {

    return {
        ...data,
        c: data.c ?? []
    }
}

//Error because the 'c' field is also checked, but it is not an array. How to check for arrays only?

`

Thanks in advance

I assume that the problem can be solved with tuples, however, no matter how I tried, it did not work out

CodePudding user response:

Try this:

type ArrayKeyof<T> = {
  [P in keyof T]-?: any[] extends T[P] ? P : never;
}[keyof T];

export type ArrayRequired<T> = Omit<T, ArrayKeyof<T>> & Required<Pick<T, ArrayKeyof<T>>>;

// demo

interface IExample {
    a: number,
    b?: string,
    c?: number[]
}

const d: ArrayRequired<IExample> = {
  a: 1,
  c: [1],
}

See demo here.

CodePudding user response:

I have this approach:

In case you want to keep all required types as they are can use KeepAllSameButArraysRequired but if you want them to be optional and only require arrays use OnlyArrayRequired

interface IExample {
    a: number,
    b?: string,
    c?: number[]
}
type ArrayKeys<T> = {
    [K in keyof T]: Array<any> extends T[K] ? K : never
}[keyof T];

type OnlyArrayRequired<T extends object> = Partial<T> & Pick<Required<T>, ArrayKeys<T>>

type KeepAllSameButArraysRequired<T extends object> = T & Pick<Required<T>, ArrayKeys<T>>


const testOnlyArray: OnlyArrayRequired<IExample> = {
    c: [] // ok
}

const testKeepingRequriedTypesButNowArrayIsRequired: KeepAllSameButArraysRequired<IExample> = {
    a: 4, // Now need "a"
    c: [] // ok
}
  • Related