我有这个代码:
'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;
}
我希望
tsc
会抛出错误,即 Foo 类型的返回值中至少缺少 a
属性。但这并没有发生。如果我使用这条线:const rv = { };
,那么它会抛出,但是关于两个道具:a
和b
,哪个更好。
但是为什么它不与
Object.create(null)
一起抛出?
我是否使用
Required<>
类型并不重要。
我们来看看
Object.create()
官方定义:
/**
* Creates an object that has the specified prototype or that has null prototype.
* @param o Object to use as a prototype. May be null.
*/
create(o: object | null): any;
/**
* Creates an object that has the specified prototype, and that optionally contains specified properties.
* @param o Object to use as a prototype. May be null
* @param properties JavaScript object that contains one or more property descriptors.
*/
create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;
正如我们所看到的,它有两个重载,都接受
object | null
。这就是为什么你在传递 null
时不会收到错误。两个重载都会返回 any
,因此设置属性也不会引发任何错误。