0

In a recent coding situation, I found out that (A)onPress?(): void is a valid alternative for (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, ? 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? 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: () => {}
}

1 Answer 1

1

A is just syntax sugar for B in this case. I believe it's based on ES6 object initializers, which support using onPress() {...} for a function value. However since you're creating a type, TypeScript is only concerned with types and not implementations, so {...} is replaced with : type.

Personally I prefer A, as it's shorter, more consistent with ES6, and looks more like a property type in TypeScript.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.