Home > OS >  reference to partial object in typescript?
reference to partial object in typescript?

Time:02-12

I have an object and it's typed

interface formDataType {
  tesla: {
    made: string
  },
  ford: {
    made: string
  }
}
const formData: formDataType = {
    "tesla": {
      "made":"2021"
    },
    "ford": {
      "made": "2022"
    }
  };

then I've a function where its argument is one of [string]:{made: string}, how can I use back formDataType? is there something like objectOf formDataType?

demo https://codesandbox.io/s/react-typescript-forked-cwv9p

CodePudding user response:

You can create a type to use in your FormDataType, then reuse that type in your function:

TS Playground

type VehicleDetails = { made: string };

type FormDataType = {
  ford: VehicleDetails;
  tesla: VehicleDetails;
};

// The following is the same type, written using the Record utility:
// type FormDataType = Record<'ford' | 'tesla', VehicleDetails>;

const formData: FormDataType = {
  tesla: {made: '2021'},
  ford: {made: '2022'},
};

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}


Update in response to your comment:

You can also derive a union of all the types of the values of the keys in your FormData type (and if they're all the same type, the union will effectively be that one type):

TS Playground

type FormDataType = {
  ford: { made: string };
  tesla: { made: string };
};

type VehicleDetails = FormDataType[keyof FormDataType];

function doSomethingWithVehicleDetails (details: VehicleDetails) {
  // console.log(details);
}

  • Related