Skip to content

Strict null checks, index signatures, and optional properties. #17277

Closed
@sccolbert

Description

@sccolbert

This may be related to #13778

I want to define a type which restricts the allowable values of properties to a specific set of types. Sub-types may define certain properties to be a more specific subset of the allowable types (think JSON object but with well-formed, known keys).

The code below is a simplified demonstration, but I run into problems with sub-types specifying optional properties when strictNullChecks is turned on. Compilation fails with a message saying the property is incompatible with the index signature. It strikes me as odd that this is not allowed, at the same time the index signature does not have an implicit undefined . If anything, the well typed property is more safe than using the index signature. My intuition is not than an index signature should have an implicit undefined, but that the below code should be allowed with strictNullChecks. I realize that foo?: T is treated the same as foo: T | undefined by the compiler, but there is a distinct difference between the lack of presence of key, and a key with undefined as a value. Usually the distinction doesn't matter, but in this case it does.

TypeScript Version: 2.4.0

Code

interface Thing {
  [key: string]: string | number | boolean;
}

interface Other extends Thing {
  bar: boolean;  // always okay
  foo?: string;  // not okay with strictNullChecks
}

Expected behavior:
Compiles with strictNullChecks

Actual behavior:
Does not compile with strictNullChecks

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