简体   繁体   English

打字稿array.map丢失返回类型

[英]typescript array.map lost returned type

I would expect a type error in the following code, but for typescript is perfectly ok, can you tell me why? 我可能会在以下代码中遇到类型错误,但是对于打字稿来说完全可以,您能告诉我为什么吗?

export interface Structure {
    aaa: string;
}

export function f1(): Structure[] {  // OK for typescript, not for me
    const result = [].map(certState => {
        return {
            aaa: 'aaa',
            ADDITIONAL_FIELD: 'asdf'
        }
    });

    return result;
}

export function f2(): Structure[] { // ERROR for typescript (and for me)
        return [
            {
                aaa: 'sdf',
                ADDITIONAL_FIELD: 'asdf'
            }
        ]
    }

Here is the link 链接在这里

Thanks! 谢谢!

The error is due to the fact that in f2() you are directly returning your result. 该错误是由于您在f2()中直接返回结果这一事实造成的。

If you changed f2() to be 如果将f2()更改为

export function f2(): Structure[] {
    const returnVal = [
        {
            aaa: 'sdf',
            ADDITIONAL_FIELD: 'asdf'
        }
    ]

    return returnVal;
}

then there would be no compiler error. 那么就不会有编译器错误。

TypeScript uses structural typing to determine type compatibility, so in your code for f1() , result is of type TypeScript使用结构化类型确定类型兼容性,因此在f1()代码中, result为类型

{
   aaa: string,
   ADDITIONAL_FIELD: string
}[]

which is compatible with Structure[] (there is no danger in type narrowing). Structure[]兼容(类型变窄没有危险)。

I'm not 100% sure why directly returning doesn't work, but my assumption is that in f2() you are telling the compiler that "this specific array is of type Structure[] " and it says no it's not. 我不确定100%为什么直接返回不起作用,但是我的假设是在f2()您告诉编译器“此特定数组的类型为Structure[] ”,并且说不,不是。 When you have an intermediate variable in f1() you are saying "this function returns Structure[] " and when you return the intermediate variable the compiler checks and says "okay result matches Structure[] " so this function is doing what it says. 当您在f1()有一个中间变量时,您将说“此函数返回Structure[] ”,而当您返回中间变量时,编译器将检查并说“好的resultStructure[]匹配”,因此此函数将按照其说明进行操作。

I'd be curious to hear if others have a more rigorous explanation 我很想知道其他人是否有更严格的解释

I just learn that Typescript has a concept of exact types only for object literals, so f1 is not using object literals, so additional properties cannot be add and it's valid for typescript. 我只是了解到Typescript具有仅用于对象文字的精确类型的概念,因此f1不使用对象文字,因此无法添加其他属性,并且对typescript有效。 f2 uses object literals, so additional properties are not allowed. f2使用对象文字,因此不允许使用其他属性。 This scare me a lot, but that's how typescript works 这让我很害怕,但这就是打字稿的工作方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM