2
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})?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You may also want to provide a link to microsoft/TypeScript#7481, the (probably) canonical feature request for this behavior to be supported purely at the type level (rather than needing an identity function at runtime).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.