0

I have the following JSON which I have no control over:

{
    "date": "2020-01-01T00:00:00",
    "a": 0,
    "b": 0,
    "c": 0
}

Instead of specifying an interface:

interface Foo {
    date: Date,
    "a": number,
    "b": number,
    "c": number
}

I want to be able to statically type the payload like so:

type Age = "a";
type Salary = "b";
type Height = "c"

type Foo = Record<"date", Date> | Record<Age | Salary | Height, number>;

Even though the compiler seems happy but when I try to get the date from the object I get the following error:

const foo = {
        "date": "2020-01-01T00:00:00",
        "a": 0,
        "b": 0,
        "c": 0
    } as Foo;

Element implicitly has 'any' type.

If I remove the Record<Age | Salary | Height, number> then the error goes away.

1
  • can you specify which element reported to implicitly has any type ? Commented Apr 13, 2020 at 11:52

1 Answer 1

1

You should use intersection instead of union:

type Foo = Record<"date", string> & Record<Age | Salary | Height, number>

Playground


** I've changed date type to string because you're assigning string value to this field

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.