如果我有一些类似这样的代码:
type Bravo = {
b?: string;
}
type Charlie = {
c:Bravo['b']
}
function acceptsCharlie(value: Charlie){
//'value.c' is possibly 'undefined'.(18048)
value.c.split('');
}
这是有道理的——该类型Charlie
从继承了可选字符串Bravo
。
我们可以通过使用Required
实用程序类型来解决这个问题:
type Bravo = {
b?: string;
}
type Charlie = {
// 👇
c:Required<Bravo>['b']
}
function acceptsCharlie(value: Charlie){
// no error here
value.c.split('');
}
简单的。
但是,如果我再添加一层键入查找:
type Alpha = {
a?: string;
}
type Bravo = {
b: Alpha['a'];
}
type Charlie = {
c: Required<Bravo>['b']
}
function acceptsCharlie(value: Charlie){
//'value.c' is possibly 'undefined'.(18048)
value.c.split('');
}
这Required
不再能解决我的问题。
怎么回事?