Magic Lasso
Magic Lasso

Reputation: 1542

Typescript - way to check for existence of properties only and ignore type checking of the property itself without using any?

I have interfaces for all the different data types and those are explicity types without using 'any'. Is there any way to use type checking with those interfaces but that only compare existence of the properties of those interfaces without type checking the properties values?

Upvotes: 0

Views: 308

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

You can create a mapped type which will allow you to take your interfaces with explicit types, and produce new types with all the same properties set to any. For example:

interface StrongType {
  foo: string,
  bar: number
}

type PropertiesExist<T> = {
  [P in keyof T]: any;
}

type LooseType = PropertiesExist<StrongType>


// No error; it has all the properties, even though they're different types
const thing: LooseType = {
  foo: true,
  bar: () => {}
}

// Error: it's missing the bar property
const thing2: LooseType = {
  foo: 123,
}

Playground link

Upvotes: 2

Related Questions