镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Using a mapped type, can't Exclude "undefined" from an optional property #24067

Description

@acshef

The example below shows how one ought to be able to implement the opposite of the mapped type Partial<T>, which should remove undefined from the type of every single property in an interface.

TypeScript Version: 2.9.0-dev.201xxxxx

Search Terms:
exclude undefined mapped optional

Code

type NeverUndefined<T> = {
    [K in keyof T]: Exclude<T[K], undefined>;
}

interface MyInterface {
    undef: undefined
    optionalString?: string;
    stringOrUndefined: string | undefined;
    definedString: string;
}

type NeverUndefinedMyInterface = NeverUndefined<MyInterface>;

Expected behavior:

// typeof NeverUndefinedMyInterface
interface NeverUndefinedMyInterface {
    undef: never;
    optionalString: string;
    stringOrUndefined: string;
    definedString: string;
}

Actual behavior:

// typeof NeverUndefinedMyInterface
interface NeverUndefinedMyInterface {
    undef: never;
    optionalString: string | undefined;
    stringOrUndefined: string;
    definedString: string;
}

(notice that optionalString still contains undefined in its type definition)

Playground Link:
https://www.typescriptlang.org/play/#src=type%20NeverUndefined%3CT%3E%20%3D%20%7B%0D%0A%20%20%20%20%5BK%20in%20keyof%20T%5D%3A%20Exclude%3CT%5BK%5D%2C%20undefined%3E%3B%0D%0A%7D%0D%0A%0D%0Ainterface%20MyInterface%20%7B%0D%0A%20%20%20%20undef%3A%20undefined%3B%0D%0A%20%20%20%20optionalString%3F%3A%20string%3B%0D%0A%20%20%20%20stringOrUndefined%3A%20string%20%7C%20undefined%3B%0D%0A%20%20%20%20definedString%3A%20string%3B%0D%0A%7D%0D%0A%0D%0Atype%20NeverUndefinedMyInterface%20%3D%20NeverUndefined%3CMyInterface%3E%3B

Related Issues:
None

Activity

  1. DanielRosenwasser commented on May 11, 2018

    @DanielRosenwasser
    Member

    You can never truly remove undefined from an optional property, but you remove optionality with mapped type modifiers (#21919), or use the Required type which is part of lib.d.ts now.

  2. typescript-bot commented on May 30, 2018

    @typescript-bot
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  3. locked and limited conversation to collaborators on Jul 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions