[SOLVED] typescript – how to properly extend interface with some fields overrided

Issue

I want to extend the Interface Position and update the type of its fields

export interface Position {
  expiryDate: string;
  strike: string;
  ...
}

type OverridePosition = Omit<Position, 'expiryDate|strike'> & {
  expiryDate: number;
  strike: number;
}

let positionItem:OverridePosition = {
  expiryDate: 1000000,
  strike: 2000;
  ...
}

But error throw for positionItem.

Type 'number' is not assignable to type 'never'.ts(2322)
Type.ts(37, 3): The expected type comes from property 'expiryDate' which is declared here on type 'OverridePosition'

Solution

You were close but you got the Omit wrong. The proeprty names to omit should be a union of strings, and not a single string with a pipe character.

type OverridePosition = Omit<Position, 'expiryDate' | 'strike'> & {
  expiryDate: number;
  strike: number;
}

Playground

Answered By – Alex Wayne

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *