Typescript type to object literal

Viewed 157
type SelectData = {
  name?: boolean;
  address?: boolean;
}

const selectData: SelectData = {
  name: true
}

const untypedSelectData = {
  name: true
}

I want typescript to throw an error if I try to do something like this:

const selectData: SelectData = {
  age: true
}

But I also want the type of selectData to be the same as untypedSelectData (i.e. {name: boolean})?

1 Answers

If you want a compile-time check that an object is assignable to some weaker type, while also retaining a stronger inferred type for the variable or constant it's assigned to, you can use a generic identity function.

function checkData<T extends SelectData>(data: T): T {
  return data;
}

// type is { name: true }
const selectData = checkData({
  name: true
})

// error: object literal may only specify known properties
const errorData = checkData({
  age: 23
})

Playground Link

As @jcalz notes, there is a feature request on the official GitHub tracker for a way to do this without adding the extra function declaration and function call, but at present such a feature does not exist.

Related