简体   繁体   中英

Typescript type to object literal

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 (ie {name: boolean})?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM