Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型脚本泛型类型断言_Typescript_Typescript Typings_Typescript Generics - Fatal编程技术网

Typescript 类型脚本泛型类型断言

Typescript 类型脚本泛型类型断言,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,下面是我对typescript的观察总结 下面是一些代码: type someTypeEnum = '1'; type someOtherTypeEnum = '2' | '3'; type combinedTypeEnum = someTypeEnum | someOtherTypeEnum; 第一种情况是:- function typeAssertion<T extends combinedTypeEnum>(args: T): args is someTypeEnum {

下面是我对typescript的观察总结

下面是一些代码:

type someTypeEnum = '1';
type someOtherTypeEnum = '2' | '3';
type combinedTypeEnum = someTypeEnum | someOtherTypeEnum;
第一种情况是:-

function typeAssertion<T extends combinedTypeEnum>(args: T): args is someTypeEnum {
    // The error i get
    // A type predicate's type must be assignable to its parameter's type.
    //  Type '"1"' is not assignable to type 'T'.
    return undefined;
}
我们已经收到一个错误,指出
'4'
不是有效的参数,那么为什么
args is someTypeEnum
被认为是有效的谓词

这是第二种情况:-

function typeAssertion(args: combinedTypeEnum): args is someTypeEnum {
    return undefined;
}
这似乎很好,但如果我们这样做:-

function someFunction<T extends combinedTypeEnum>(args: T): T {
    if (typeAssertion(args)) {
        // args here is  'T & "1"' 
        args
    }
    return args
};
函数someFunction(args:T):T{ if(类型断言(args)){ //这里的args是“T&“1” args } 返回参数 }; 为什么我们有T&“1”,而不仅仅是“1”,我们特别断言它是someTypeEnum

我真的很好奇为什么会做出这样的决定。
如果事情以不同的方式完成,那么看看事情是如何中断的将非常有帮助。

extends
在使用字符串文本时没有多大意义。为了便于解释,让我使用其他类型。考虑这三个类:

class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}
使用泛型时,实际类型由调用方设置:

function foo<T extends Animal>(arg: T) {}

foo(new Dog()); //T is Dog, equivalent to foo(arg: Dog) {}
foo(new Cat()); //T is Cat, equivalent to foo(arg: Cat) {}
当然,它既不起作用也没有意义


至于你的第二个例子:变量的类型没有改变。关键是,通过断言特定类型,编译器允许您对该类型执行任何可以执行的操作。

Hmmm,我想为这么晚的答复道歉,但我很好奇,在这种情况下,我们能否以某种方式使用重载。谢谢
function foo<T extends Animal>(arg: T) {}

foo(new Dog()); //T is Dog, equivalent to foo(arg: Dog) {}
foo(new Cat()); //T is Cat, equivalent to foo(arg: Cat) {}
function foo<T extends Animal>(arg: T): arg is Cat {}
function foo(arg: Dog): arg is Cat {}