有没有一种方法(类似于函数式语言中的模式匹配)来分解TypeScript中的联合类型,也就是像这样的构造:
var a: Foo | Bar = ...;
a match {
case f: Foo => //it's a Foo!
case b: Bar => //it's a Bar!
}
如果没有这样的构造--创建这样的构造有什么技术上的困难吗?
嘿,我试着区分两种等价类型:
type A = {
a: string
}
type B = {
a: string
}
有两个类型的谓词:
function isA(obj: any): obj is A {
return true
}
function isB(obj: any): obj is B {
return true
}
但是我面临一个问题,当应用到一个联合类型时,每个谓词都会捕获这两种类型。
下面是一个例子:
这是故意的行为吗?如果是,用例是什么?
我有一个工厂,它根据扩展BaseEntity的实体返回配置值。但是,我收到一个类型错误,它表示不能从函数(特别是type Collection<A> is not assignable to type Collection<T>和那个Type A is not assignable to type T )返回与泛型参数具有相同签名的类型。但是,在这个示例中,A和T没有相同的定义吗?
type BaseTypes = 'a';
interface Base {
type: BaseTypes;
id: number;
}
interface A
我得到了这个错误的Argument of type 'string' is not assignable to parameter of (a list of strings)。
useEffect(() => {
if (selectedConnection) {
wallet.connect(selectedConnection)
}
}, [selectedConnection])
selectedConnection是一个字符串,而wallet.connect接受一个字符串。
我已将其更改为
selectedConnect
我有一个模态数据接口 interface ModalData {
...
payload: any; // At any given time, this payload might be a string or number or boolean;
...
} 在模式数据有效负载中有不同类型的可能性,因此我创建了另一个类型: type IPayLoad = string | number | boolean; 现在,当我在我的代码中使用这些类型时,我得到了下面的错误。 问题是我不喜欢将any类型设置为上面的有效负载。但是如果我将它设置为IPayLoad类型,我会得到下面的错误。 th
因此,我试图写一个道具类型格式,其中如果一个被选择,另一个支柱将被丢弃。
type ButtonProps = {
to: string,
} | {
onClick: (() => void)
};
export const BackButton = (props: ButtonProps) => {
if(props.to != null) {
//props {to} will be used hence no need for onClick
}
else {
// {onClick} will be used over {
我试着用类型保护缩小一个复杂的类型。我希望类型保护的假分支能够将理解为缩小的类型。
interface Model { side: 'left' | 'right'; }
interface LeftModel { side: 'left'; }
interface RightModel { side: 'right'; }
type Either = LeftModel | RightModel;
function isLeft(value: Either): value is LeftModel { // else is R
尝试编写一个函数,以便在发生意外的“失败”时优雅地返回。我考虑在这个函数上使用go风格的返回值,并将返回值键入为[Val, null] | [null, Error]。
但是,当尝试使用if语句对返回值进行类型保护时,
const [val, err] = myFunc(); // => [Val, null] | [null, Error]
if (err) {
handle(err);
return;
}
// At this point in code, return value has to be of type [Val, null]
doSomethingWit
在下面的程序中,联合U有两个字段a和b,每个字段都具有不同的默认值。如果使用聚合初始化U创建类型为{}的变量,那么联合的值和活动成员是什么?
#include <iostream>
struct A { int x = 1; };
struct B { int x = 0; };
union U {
A a;
B b;
};
int main() {
U u{};
std::cout << u.a.x;
}
令人惊讶的是,编译器在这里分歧: Clang打印1和GCC打印0,演示:
在其中一个编译器中是否存在bug,或者这里的行为不是
以后是否可以正确检查事件类型,以便下面的代码成为安全类型。因为现在会发出以下警告:
Property 'key' does not exist on type 'ClipboardEvent'
Property 'clipboardData' does not exist on type 'KeyboardEvent | ClipboardEvent'.
Property 'clipboardData' does not exist on type 'KeyboardEvent'.ts(23
TypeScript在推断类型保护的联合类型时似乎有问题。例如,考虑一个将类型保护数组与以下签名组合在一起的函数
function combine<T>(guards: ((x: any) => x is T)[]): (x: any) => x is T
并考虑具有不同属性的A和B的以下类型保护
function isA(x: any): x is A
function isB(x: any): x is B
现在,我希望combine([isA, isB])可以工作,并具有推断的类型(x: any) => x is A | B,但是我得到了一个错误,指出((x