0

So lets say i have two interfaces

interface InterfaceOne {
     myString: string,
     myNum: number
}

interface interfaceTwo extends InterfaceOne {
     myBool: boolean
}

with the following typescript code

let somedata: interfaceTwo = {
     myString: "hello world",
     myNum: 42,
     myBool: false

is there a way I can convert somedata into a InterfaceOne while removing the key myBool from the object?

Zachary Pike
  • 13
  • 1
  • 2
  • Every `InterfaceTwo` is an `InterfaceOne` so you don't have to remove anything from `somedata` to get that to happen. But no matter what you do with interfaces, it won't affect the object at runtime; the type system from TS is erased upon compiling to JS. If you want to delete properties you will have to do that explicitly. See [this code](https://tsplay.dev/NDG8Vw). – jcalz Aug 15 '21 at 00:00
  • Possible duplicate of https://stackoverflow.com/questions/55704071/how-to-omit-a-property-from-a-type – jcalz Aug 15 '21 at 00:01

1 Answers1

0

you can, but not how you have it. you are hardcoding InterfaceTwo in yow code, if you remove myBool it wont become interfaceOne, thats not how Object Oriented Programing works, instead it will throw an error. if you want yow var to be either A or B do not extend use both

interface InterfaceOne {
    myString: string,
    myNum: number
}

interface InterfaceTwo {
    myBool: boolean
}


let somedata: InterfaceOne | InterfaceTwo = {
    myString: "hello world",
    myNum: 42,
    myBool: false
}
Ernesto
  • 3,944
  • 1
  • 14
  • 29