0

I have this TypeScript code:

type MyType1 = {
    prop1: number,
    prop2: string,
    prop3: string
}
type MyType2 = {
    prop1: number,
    prop2: string
}
const objOfType1 = { prop1: 1, prop2: "hello world", prop3: "should be removed" } as MyType1;
console.log('objOfType1', objOfType1);

const objOfType2 = objOfType1 as MyType2;
console.log('objOfType2', objOfType2);

const objOfType2Copy = { ...objOfType2 };
console.log('objOfType2Copy', objOfType2Copy);

The output in all 3 cases is the same

objOfType1, objOfType2, and objOfType2Copy all have the same 3 properties. I was expecting that output for both objOfType2 and objOfType2Copy won't contain prop3 property.

How can I achieve the "expected" behavior?

dnk.nitro
  • 496
  • 6
  • 13
  • Use a class. Compiler won't complain about extra properties on types and interfaces. You also seem to be confusing compile-time with run-time: the typescript compiler doesn't do things like remove properties from objects. All it does is tell you if your program adheres to the rules you've chosen. – Jared Smith Aug 23 '19 at 21:50

1 Answers1

4

You seem to misunderstanding how work Typescript.

Typescript is a superset of Javascript. It gives static typing which permit to check your code before the runtime and enforce code quality & understandability.

Typescript is compiled to Javascript. All the Typescript specific code is removed from the final JS code: all types. Your browser cannot run Typescript code, it runs the compiled Javascript one.

So your code compiled to JS gives something like that:

const objOfType1 = { prop1: 1, prop2: "hello world", prop3: "should be removed" }
console.log('objOfType1', objOfType1);

const objOfType2 = objOfType1;
console.log('objOfType2', objOfType2);

const objOfType2Copy = { ...objOfType2 };
console.log('objOfType2Copy', objOfType2Copy);

As you can see all types and references to them were removed: only stay the JS part. Typescript is only here to structure your code, he's the dev part.

When you use the as keyword, you just tell to the TS compiler "ok dude, this variable is THIS type". You don't modify anything about its value. It's just a static type cast.

Typescript doesn't exist in runtime. So when you code in Typescript, you have to always have in mind "what this code is doing in runtime ?"

Richard Haddad
  • 904
  • 6
  • 13