假设我有一个只有两个子容器的弹性容器,并且我想让它们收缩,所以我给它们都指定了一个非零flex-shrink值。据我了解,重要的是值之间的比率。因此,将值设置为:
都应该产生相同的行为。它确实如此……直到其中一个孩子按下了它min-width。在第三种情况下,第二个孩子溢出了容器。我想说这是一个错误,但它在 Chrome、Safari 和 Firefox 中都是一致的。
这是一个游乐场,这是显示“错误”的屏幕截图,我在其中添加了每个孩子的尺寸。每个子width属性设置为 200px 和min-width100px。第一种情况下容器的宽度为 300px,第二种情况为 220px。
body {
background: black;
color: white;
}
.container {
border: deeppink 2px solid;
display: flex;
height: 50px;
}
.box {
width: 200px;
min-width: 100px;
}
.green {
background: green;
}
.blue {
background: blue;
}Run Code Online (Sandbox Code Playgroud)
<h2>First case, both boxes have pixels to give up</h2>
<h3>Flex shrink 4 and …Run Code Online (Sandbox Code Playgroud)考虑这个简单的片段。我也把它粘贴在这里:
type A =
| {
b: number;
}
| {
c: number;
};
function f1(a: A) {
if ('b' in a) {
return a['b']; // No problem!
}
return 42;
}
function f2(a: A) {
const key = 'b';
if (key in a) {
return a[key]; // Property 'b' does not exist on type 'A'
}
return 42;
}
Run Code Online (Sandbox Code Playgroud)
为什么 of 的类型没有a缩小为{b: number}in f2?(因为它是为了f1)
检查我在某处找到的这个打字稿 4.2 片段(此处为游乐场):
type BlackMagic<T> = { [K in keyof T]: BlackMagic<T[K]> }
declare const foo: BlackMagic<{q: string}>;
declare const str: BlackMagic<string>;
declare const num: BlackMagic<12>;
Run Code Online (Sandbox Code Playgroud)
我无法绕过它。TS 如何处理?怎么不陷入无限递归?具体来说,在strand的情况下num,将鼠标悬停在变量上表明 TS 正在将类型解析为 just stringand 12。怎么会这样?
我刚刚遇到了让我感到惊讶的事情。考虑以下四个函数:
function A() {
this.q = 1;
}
function B() {
this.q = 1;
return this;
}
function C() {
this.q = 1;
return 42;
}
function D() {
this.q = 1;
return {};
}
Run Code Online (Sandbox Code Playgroud)
让我们new从所有对象中创建对象(通过):
console.log('a', new A());
console.log('b', new B());
console.log('c', new C());
console.log('d', new D());
Run Code Online (Sandbox Code Playgroud)
这是输出:
a A { q: 1 }
b B { q: 1 }
c C { q: 1 }
d {}
Run Code Online (Sandbox Code Playgroud)
前三个似乎表明函数返回什么并不重要,JS 只关心每个函数的作用this(这是我以前的信念,顺便说一句)。但最后一个与此相反。
那么,这里发生了什么?我修改后的规则是“如果函数返回一个Object,我们保留它。否则,我们保留this”。但我对此感到非常不确定。
我正在尝试了解 Typescript 中的函数重载如何工作,但我不明白。检查此代码片段 ( ts Playground )(仅使用一个声明以使其尽可能简单):
function foo(x: number): 42
function foo(x: number) {
return x
}
const y = foo(23)
Run Code Online (Sandbox Code Playgroud)
有两件事不对劲:
y的推断值为42相反,如果我只是在函数实现上声明返回类型,则事情会按预期工作(或失败!):
function foo(x: number): 42 {
return x // -> Type 'number' is not assignable to type '42'.(2322)
}
const y = foo(4)
Run Code Online (Sandbox Code Playgroud)