The code below defines a TypedDict with optional keys.
The if statement in the middle raises an exception if a certain key is absent, which means that the next lines will be executed only if that key is present. It seems Pylance can't figure out this logic automatically. How am I supposed to handle this? Reassign a new typing to the same Dict somehow?
output_dict_type = TypedDict(
'some description',
{
'id': str
'name': str
},
total=False
)
my_dict:output_dict_type = {
'id': 'foo'
}
if not my_dict.get('name'):
raise Exception('name is required')
if my_dict['name'] == 'John': # type error: "name" is not a required key...
do_stuff()