Skip to content

Type check loosening when using Record with union types.Β #51298

Closed
@elementum

Description

@elementum

Bug Report

Under certain conditions typescript compiler allows setting any value for a record that has union type key. See code section below.

πŸ•— Version & Regression Information

Tested in 4.8.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type UnionType = "ABC" | "XYZ"
type RecordType = Partial<Record<UnionType, string>>

// no errors, ok
const value1: RecordType = {
    XYZ: "some value",
}

// error, ok, number where string is expected
const value2: RecordType = {
    XYZ: 123,
}

// error, ok, number where string is expected
const value3: RecordType = {
    ["XYZ"]: 123
}

// error, ok, key test is not allowed
const value5: RecordType = {
    ["test"]: 123
}


// as UnionType clause is important
// it could be a function that returns UnionType, e.g. const key = getUnionKey(), same problem
const key: UnionType = "XYZ" as UnionType

// no error, but it should be there
const value4: RecordType = {
    [key]: 123
}

πŸ™ Actual behavior

No error when using square brackets. Last example.

πŸ™‚ Expected behavior

It should throw an error.

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