Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript interface: optional but not undefined

Tags:

typescript

How can I describe type like

key is optional, but if it existed, it cannot be undefined.

At the first time, I'm using Partial to make all properties of T optional.

interface A {
  a: number;
}

var data: A = {
  a: 1,
}

var update1: Partial<A> = {

}

var update2: Partial<A> = {
  a: undefined
}

var result1: A = {
  ...data,
  ...update1,
} // { a: 1 }

var result2: A = {
  ...data,
  ...update2,
} // { a: undefined }

The problem here is that result2 is not implementing interface A in runtime, but typescript never complains about it. Is it bug or feature? I guess typescript not working well with spread operator...

The goal is distinguish these two variable using typescript!


var data: T = {
  a: 1,
  b: 2,
}

var optional1: MyPartial<T> = { // Totally OK

}

var optional2: MyPartial<T> = { // OK
  a: 3,
}

var optional3: MyPartial<T> = { // OK
  b: 4,
}

var optional4: MyPartial<T> = { // OK
  a: 3,
  b: 4,
}

var undef1: MyPartial<T> = { // typescript must throw error
  a: undefined,
}

var undef2: MyPartial<T> = { // typescript must throw error
  a: 3,
  b: undefined
}

...

Check this out TypeScript playground example.

like image 500
Kim Hyung-jun Avatar asked Jan 18 '19 02:01

Kim Hyung-jun


1 Answers

Support now exists in 4.4.0 via --exactOptionalPropertyTypes

So by default, TypeScript doesn’t distinguish between a present property with the value undefined and a missing property ...

In TypeScript 4.4, the new flag --exactOptionalPropertyTypes specifies that optional property types should be interpreted exactly as written, meaning that | undefined is not added to the type:

https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/#exact-optional-property-types

like image 91
cdosborn Avatar answered Oct 02 '22 14:10

cdosborn