Advanced TypeScript Exercises - Question 7
Pragmatic Maciej
Posted on March 11, 2020
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.
Posted on March 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024