I'm trying to implement optional parameters in interface, however I get an error TS2532: Object is possibly 'undefined'., is there any way to implement optional properties like in this doc
Here are my interfaces:
// Local interface
interface SecondaryIndex {
secondaryIndexName: string;
addLocalSecondaryIndex: boolean;
}
// Exported Interface
export interface ILambdas extends cdk.StackProps {
...
secondaryIndex?: SecondaryIndex
}
Error: TS2532: Object is possibly 'undefined':
if (props.secondaryIndex.addLocalSecondaryIndex) {
...
}
CodePudding user response:
Javascript's optional chaining operator (?.
) to the rescue!
if (props.secondaryIndex?.addLocalSecondaryIndex) {
...
}
With ?.
, if secondaryIndex
is undefined
your conditional expression evaluates to undefined
rather than throwing an Error. Typescript will be happy.