Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript force implementation of optional interface members [duplicate]

Tags:

typescript

Given an interface

interface IAmOptional {
   optional? : string,
   optional2?: string
   forced: string
}

Is there a way to covert, extend or similar IAmOptional in a way that this implementation fails?

class someClass {
    thisShouldHaveAllKeys : IAmOptional  = { // Forced<IAmOptional> ??
        forced: 'i am forced'
    }  // Here I want an error like 'thisShouldHaveAllKeys does not have optional and optional2' 
}
like image 615
distante Avatar asked Jan 25 '19 15:01

distante


People also ask

How do you declare an optional member of an interface in TypeScript?

The declaration of the interface is a place to make some properties optional. You can achieve that with a question mark next to the properties names. In the above example, the pet is an optional property.

Can we have interface with optional and default properties in TypeScript?

In TypeScript, interfaces represent the shape of an object. They support many different features like optional parameters but unfortunately do not support setting up default values. However, you can still set up a TypeScript interface default value by using a workaround.

How do I make all properties in a TypeScript interface optional?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!

How do I override interface properties in TypeScript?

Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.


1 Answers

Yes, starting with TypeScript 2.8 there is a way to programmatically remove the optional modifier from properties using the -? syntax with mapped types:

type Required<T> = { [K in keyof T]-?: T[K] }

This gives you the behavior your want:

class someClass {
  thisShouldHaveAllKeys: Required<IAmOptional> = {  // error!
//~~~~~~~~~~~~~~~~~~~~~ <-- missing properties optional1, optional2
    forced: 'i am forced'
  }
}

In fact, this Required type alias is so useful that it's predefined for you in the standard library. So you can just use it without defining it.

Hope that helps. Good luck!

like image 179
jcalz Avatar answered Sep 28 '22 14:09

jcalz