繁体   English   中英

工厂函数的命名返回类型?

[英]Named return types for factory functions?

我目前可以使用接口和命名类型来描述工厂函数的返回值

interface Thing {
    thing: string
}

const create = (): Thing => ({
    thing: 'sdf'
})

在没有命名返回类型的情况下,TypeScript 会从返回值中推断出类型 - 但是该类型未命名并且在我的编辑器中阅读起来很混乱。

是否可以在工厂函数中命名返回类型?

我在想象类似的东西

const create = () => ({
    thing: 'sdf'
} as Thing)

您可以将create变量的类型描述为返回Thing的函数:

const create: () => Thing = () => ({
    thing: 'sdf'
});

有时做这样的事情会很好:

function foo() { // ❌
    interface Foo {x: number, y: number}
    return {x: 4, y: 5} as Foo
}

或这个:

function foo(): Foo { // ❌
    interface Foo {x: number, y: number}
    return {x: 4, y: 5}
}

因为它可以让你命名你的返回类型,而不会混淆模块级类型。 但是,两者都给出了编译时错误:

Return type of exported function has or is using private name 'Foo'.

最后,这根本没有解析:

// ❌
function foo(): (interface Foo {x: number, y: number}) {
    return {x: 4, y: 5}
}

所以你被困在模块级别。 请注意,虽然不需要导出类型。

interface Foo {x: number, y: number}
export function foo(): Foo { // perfectly fine
    return {x: 4, y: 5}
}

暂无
暂无

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

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