Skip to content

Index signature required in interface but not in object type #30345

Closed
@calebmer

Description

@calebmer

TypeScript Version: 3.3.3

Search Terms: index signature, interface, object type

Code

interface A {
    p: number,
    q: string,
}

type B = {
    p: number,
    q: string,
};

type JSONObjectValue = {
    [key: string]: number | string,
};

declare const a: A;
declare const b: B;

const jsonA: JSONObjectValue = a;
const jsonB: JSONObjectValue = b;

Expected behavior: Both a should be assignable to jsonA and b should be assignable to jsonB.

Actual behavior: jsonA = a errs but jsonB = b does not err.

Playground Link


Use case: I have a type JSONValue (which I’ve seen before in some DefinitelyTyped libraries) to make sure an object is a valid JSON value. Which would mean it doesn’t contain functions or other problematic properties.

export type JSONValue = null | boolean | number | string | JSONArrayValue | JSONObjectValue;
export interface JSONArrayValue extends ReadonlyArray<JSONValue> {}
export type JSONObjectValue = {readonly [key: string]: JSONValue};

I also have some interfaces which inherit from each other using extends which should be valid JSON values. Which is why I would prefer to use an interface over an object type in this case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions