Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check property existance before accessing it #243

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 46 additions & 28 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ function typeOf(varName: string, type: string): string {
return eq(`typeof ${varName}`, `"${type}"`)
}

function inOp(propName: string, varName: string): string {
return `"${propName}" in ${varName}`
}

function not(statement: string): string {
return `!(${statement})`
}

function typeUnionConditions(
varName: string,
types: Type[],
Expand Down Expand Up @@ -412,6 +420,7 @@ To disable this warning, put comment "${suppressComment}" before the declaration
...declaration.getMethods(),
].map(p => ({
name: propertyName(p),
isOptional: p.hasQuestionToken(),
type: p.getType(),
}))
conditions.push(
Expand Down Expand Up @@ -464,6 +473,7 @@ To disable this warning, put comment "${suppressComment}" before the declaration
: p.getTypeAtLocation((typeDeclarations || [])[0])
return {
name: p.getName(),
isOptional: p.isOptional(),
type: typeAtLocation,
}
})
Expand Down Expand Up @@ -730,15 +740,15 @@ function typeConditions(

function propertyConditions(
objName: string,
property: { name: string; type: Type },
property: { name: string; isOptional: boolean; type: Type },
addDependency: IAddDependency,
project: Project,
path: string,
arrayDepth: number,
records: readonly IRecord[],
outFile: SourceFile,
options: IProcessOptions
): string | null {
): string {
const { debug } = options
const propertyName = property.name

Expand All @@ -747,18 +757,28 @@ function propertyConditions(
const propertyPath = `${path}["${strippedName}"]`

let expectedType = property.type.getText()
const conditions = typeConditions(
varName,
property.type,
addDependency,
project,
propertyPath,
arrayDepth,
true,
records,
outFile,
options
const hasPropertyCondition = inOp(strippedName, objName)
let conditions = ands(
...([
hasPropertyCondition,
typeConditions(
varName,
property.type,
addDependency,
project,
propertyPath,
arrayDepth,
true,
records,
outFile,
options
),
].filter(v => v != null) as string[])
)
if (property.isOptional) {
conditions = ors(not(hasPropertyCondition), conditions)
}

if (debug) {
if (expectedType.indexOf('import') > -1) {
const standardizedCwd = FileUtils.standardizeSlashes(process.cwd())
Expand All @@ -776,7 +796,7 @@ function propertyConditions(

function propertiesConditions(
varName: string,
properties: ReadonlyArray<{ name: string; type: Type }>,
properties: ReadonlyArray<{ name: string; isOptional: boolean; type: Type }>,
addDependency: IAddDependency,
project: Project,
path: string,
Expand All @@ -785,21 +805,19 @@ function propertiesConditions(
outFile: SourceFile,
options: IProcessOptions
): string[] {
return properties
.map(prop =>
propertyConditions(
varName,
prop,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
return properties.map(prop =>
propertyConditions(
varName,
prop,
addDependency,
project,
path,
arrayDepth,
records,
outFile,
options
)
.filter(v => v !== null) as string[]
)
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { testProcessProject } from '../generate'

testProcessProject(
'generated type guards for unions with disjoint properties',
{
'test.ts': `
export type X = { key1: string } | { key2: number }
`,
},
{
'test.ts': null,
'test.guard.ts': `
import { X } from "./test";

export function isX(obj: unknown): obj is X {
const typedObj = obj as X
return (
((typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
"key1" in typedObj &&
typeof typedObj["key1"] === "string" ||
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
"key2" in typedObj &&
typeof typedObj["key2"] === "number")
)
}`,
},
{ options: { exportAll: true } }
)
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,23 @@ testProcessProject(
import { Foo } from "./test";

export function isFoo(obj: unknown): obj is Foo {
const typedObj = obj as Foo
return (
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
( typeof typedObj["foo"] === "undefined" ||
typeof typedObj["foo"] === "number" ) &&
( typeof typedObj["bar"] === "undefined" ||
typeof typedObj["bar"] === "number" ) &&
( typeof typedObj["baz"] === "undefined" ||
typeof typedObj["baz"] === "number" )
)
const typedObj = obj as Foo
return (
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
( !("foo" in typedObj) ||
"foo" in typedObj &&
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

!("foo" in typedObj) || "foo" in typedObj && // ...

This check seems redundant, given that the previous code handled this case just fine.

(typeof typedObj["foo"] === "undefined" ||
typeof typedObj["foo"] === "number" )) &&
"bar" in typedObj &&
( typeof typedObj["bar"] === "undefined" ||
typeof typedObj["bar"] === "number" ) &&
( !("baz" in typedObj) ||
"baz" in typedObj &&
(typeof typedObj["baz"] === "undefined" ||
typeof typedObj["baz"] === "number" ))
)
}`,
}
)
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ testProcessProject(
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
"foo" in typedObj &&
typeof typedObj["foo"] === "number" &&
"bar" in typedObj &&
typeof typedObj["bar"] === "string"
)
}`,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { testProcessProject } from '../generate'

testProcessProject(
'generates type guards for interface with optional field',
{
'test.ts': `
/** @see {isFoo} ts-auto-guard:type-guard */
export type Foo {
foo?: number,
bar: number | undefined,
baz?: number | undefined
}`,
},
{
'test.ts': null,
'test.guard.ts': `
import { Foo } from "./test";

export function isFoo(obj: unknown): obj is Foo {
const typedObj = obj as Foo
return (
(typedObj !== null &&
typeof typedObj === "object" ||
typeof typedObj === "function") &&
(!("foo" in typedObj) ||
"foo" in typedObj &&
(typeof typedObj["foo"] === "undefined" ||
typeof typedObj["foo"] === "number")) &&
"bar" in typedObj &&
(typeof typedObj["bar"] === "undefined" ||
typeof typedObj["bar"] === "number") &&
(!("baz" in typedObj) ||
"baz" in typedObj &&
(typeof typedObj["baz"] === "undefined" ||
typeof typedObj["baz"] === "number"))
)
}`,
}
)
Loading