Home > Back-end >  How do I make typescript utility type Required work for the nested members?
How do I make typescript utility type Required work for the nested members?

Time:06-19

I want to use Required and make the members not optional. It works just fine. But, it doesn't work for the nested members of the interface. Is there a way to tell typescript that all the members will not be undefined?

interface Camera {
    id? :string;
    name? : {
        firstName?:string;
        secondName? :string
    };
    site? :string
}


const firstCamera :Required<Camera> ={
    id :'1',
    name :{},
    site :'hello world'
}


The above code works fine for the first members. But, firstName and secondName are still optionals. I would like to make them mandatory fields as well. Is there a way? Thanks in advance

CodePudding user response:

You can split the Camera interface. Create some type Name and put names. For the Camera interface create a generic. Then use the utility twice. TS Playground

type Name = {
    firstName?: string;
    secondName?: string;
}
interface Camera<T> {
    id?: string;
    name?: T;
    site?: string;
}
const firstCamera :Required<Camera<Required<Name>>> ={
    id:'1',
    name:{},
    site :'hello world'
}

CodePudding user response:

You could remove conditional modifiers on the firstName, secondName properties of name. Name is still optional but if it's included firstName & secondName have to be too.

interface Camera {
    id?: string;
    name?: {
        firstName: string;
        secondName: string
    }
    site?: string
};
  • Related