Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if interface has property?

Need to check if interface has specific property. Tried/googled, but could not find appropriate solution. For example;

interface Props {
  id: string;
  name: string;
  age: number;
}

What is best way to check if Props has "age" property?

like image 597
ZAM Avatar asked Feb 04 '26 16:02

ZAM


1 Answers

If what you're looking for is checking if a key exists at compile time in a type, you can use something like this:

type ContainsKey<T, K extends string | number> = T extends { [key in K]: any }
  ? true
  : false

type contains1 = ContainsKey<Props, 'age'> // type contains1 = true
type contains2 = ContainsKey<Props, 'foo'> // type contains2 = false
like image 73
g2jose Avatar answered Feb 06 '26 06:02

g2jose