Advanced TypeScript Exercises - Question 7

macsikora profile image Maciej Sikora ・2 min read

Today's question will be about creating exclusiveness behavior of the type. TypeScript is structurally typed language, very important is to mention that also types compatibility in TypeScript is based on structural subtyping. That property is visible during assignment and during passing of arguments to functions. Short explanation would be - we can assign or pass values which have at least the same members as wanted type, but also they can have more constraints. More about that in TS documentation.

Our task is to make types more strict and block possibility of passing/assigning subtypes.

7.1 Make a type which will only allow for assignment of an empty object

type EmptyObject = {} // empty object only, 🔥 change the type to be exclusive for any field 

// test cases
const shouldPass: EmptyObject = {}; // this should be ok 🟢
const shouldFail: EmptyObject = {
    prop: 1 // here we should have compile error 🛑 

7.2 Change function type to be exclusive for its arguments

type SomeType =  {
    prop: string
// change below function type definition 🔥 in order to allow only strict SomeType value
function takeSomeTypeOnly(x: SomeType) { return x }

// test cases
const x = { prop: 'a' };
takeSomeTypeOnly(x) // this should be ok 🟢

const y = { prop: 'a', addditionalProp: 'x' };
takeSomeTypeOnly(y) // here we should have compile error 🛑 

The questions and ready to start code is available in The Playground

Post your answers in comments (preferred links to the playground). Have fun! Answer will be published soon!

This series will continue. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.


Editor guide
nombrekeff profile image
Manolo Edge

I got it, took me a while, here is the playground.

Cool exercise! I didn't know about some of the stuff I used in the solution :P

anduser96 profile image
alextsk profile image

Thanks for making me read the docs(at last))