Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
calebmer opened this issue Mar 12, 2019 · 2 comments
Closed

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

calebmer opened this issue Mar 12, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@calebmer
Copy link

calebmer commented Mar 12, 2019

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.

@jack-williams
Copy link
Collaborator

Is this covered by #15300?

@calebmer
Copy link
Author

Yes it is!

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants