Skip to content

Cannot safely, generically add a property to a record #38796

Closed
@SLaks

Description

@SLaks

TypeScript Version: v4.0.0-dev.20200525, 3.9.2

Search Terms: object intersection record

Code

function add<TShape, TName extends string, TValue>(
    obj: TShape, name: TName, value: TValue): TShape & Record<TName, TValue> {
  return {...obj, [name]: value};
}

Expected behavior:

No compiler errors

Actual behavior:

Type 'TShape & { [x: string]: TValue; }' is not assignable to type 'TShape & Record<TName, TValue>'. Type 'TShape & { [x: string]: TValue; }' is not assignable to type 'Record<TName, TValue>'.

Playground Link

Additional attempts:

I couldn't find any way to make this work without a cast; no matter what I tried, the property [name]: value is inferred as [x: string]: TValue, ignoring TName. Other attempt:

  const addition: {[name in TName]: TValue} = {[name]: value};
  return {...obj, ...addition};
Type '{ [x: string]: TValue; }' is not assignable to type '{ [name in TName]: TValue; }'.

Playground Link

Related Issues: Possibly #18538

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs More InfoThe issue still hasn't been fully clarified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions