-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
TypeScript Version: 3.4.5
Search Terms: type guard object destructuring, type guard object key
Code
export type GROUP_TYPE = 'group_1' | 'group_2';
export function isGroup(g: any): g is GROUP_TYPE {
const allowedGroups: GROUP_TYPE[] = ['group_1', 'group_2'];
return allowedGroups.indexOf(g) !== -1;
}
function getPermissions(query: { group: GROUP_TYPE }) {/* do something */ }
function goodFunction(query: { group: string }) {
if (!isGroup(query.group))
return;
const { group } = query;
return getPermissions({ ...query, group });
}
function sameFunction(query: { group: string }) {
if (!isGroup(query.group))
return;
return getPermissions(query); // Error here
// _________________^^^^^
/*
Argument of type '{ group: string; }' is not assignable to parameter of type '{ group: GROUP_TYPE; }'.
...
*/
}
Expected behavior:
Both functions (goodFunction, sameFunction) should be valid typescript code
Actual behavior:
We see TS error
Argument of type '{ group: string; }' is not assignable to parameter of type '{ group: GROUP_TYPE; }'.
Types of property 'group' are incompatible.
Type 'string' is not assignable to type 'GROUP_TYPE'.
it thinks that query.group
is steel a string
when passing as arguments, but knows it is a GROUP_TYPE
when gets it from object.
Playground Link:
link to playground
peterflynn
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created