简体   繁体   English

Typescript 中函数的类型定义

[英]Type definition for functions in Typescript

In a recent coding situation, I found out that (A) onPress?(): void is a valid alternative for (B) onPress?: () => void .在最近的编码情况中,我发现 (A) onPress?(): void是 (B) onPress?: () => void的有效替代方案。 I do prefer B over A, because it looks like it's more common in the TypeScript community and because of the consistency of defining your prop name, ?我确实更喜欢 B 而不是 A,因为它看起来在 TypeScript 社区中更常见,并且因为定义你的道具名称的一致性, ? if necessary for optional props, separated by a : and then your type.如果需要可选道具,用:分隔,然后是你的类型。

My question is: is there any documentation why A is also correct, or in which way it's different from B?我的问题是:是否有任何文档说明 A 也是正确的,或者它与 B 的不同之处? Or is it just the same?还是一样? Or is one of both more preferred?还是两者中的一个更受欢迎?

Thanks in advance!提前致谢!

type Props = {
   onPress?(): void
}

type OtherProps = {
   onPress?: () => void
}

const instanceOfProps: Props = {
    onPress: () => {}
}

const instanceOfOtherProps: OtherProps = {
    onPress: () => {}
}

A is just syntax sugar for B in this case.在这种情况下,A 只是 B 的语法糖。 I believe it's based on ES6 object initializers , which support using onPress() {...} for a function value.我相信它基于ES6 object initializers ,它支持使用onPress() {...}作为函数值。 However since you're creating a type, TypeScript is only concerned with types and not implementations, so {...} is replaced with : type .但是,由于您正在创建一个类型,TypeScript 只关心类型而不关心实现,因此{...}被替换为: type

Personally I prefer A, as it's shorter, more consistent with ES6, and looks more like a property type in TypeScript.我个人更喜欢 A,因为它更短,更符合 ES6,并且看起来更像 TypeScript 中的属性类型。

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

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