I have this code:
'use strict';
type Bar = 'a' | 'b';
type FooIntermidiate = {
[p in Bar]: string;
};
type Foo = Required<FooIntermidiate>;
console.log(getFoo());
function getFoo(): Foo {
const rv = Object.create(null);
//const rv = { };
rv.b = 'str';
return rv;
}
I expect the tsc
to throw errors that at least the a
property is missing on the returned value of type Foo. But this doesn’t happen. If I use the line: const rv = { };
then it throws, but about both of the props: a
and b
, which is better.
But why doesn’t it throw with the Object.create(null)
?
It doesn’t matter if I use the Required<>
type or not.
2
Answers
Let’s look at
Object.create()
official definition:As we can see, it has two overloadings, both accepting
object | null
. That’s why you don’t get the error when passingnull
. Both of the overloadings returnany
, so setting the property also doesn’t fire any error.Not sure your code makes a lot of sense: we don’t need
Object.create
here at all? Based on your comment thread, you can probably just declare your type, and then create your object with theas ThatType
syntax, e.g:So you just create the plain JS object you need, and then you tell TypeScript that it needs to conform to the shape you declared. And if it doesn’t, TS will yell at you about not being able to unify your plain object with the type you declared. Like when you forget to add, or intentionally leave out, one of the three requires keys.