Home > database >  typescript - how to properly extend interface with some fields overrided
typescript - how to properly extend interface with some fields overrided

Time:03-25

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'

CodePudding user response:

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

  • Related