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

Suggestion: document and enforce side effects of functions #19520

Closed
evelant opened this issue Oct 27, 2017 · 2 comments
Closed

Suggestion: document and enforce side effects of functions #19520

evelant opened this issue Oct 27, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@evelant
Copy link

evelant commented Oct 27, 2017

Allow programmers to more descriptively document the side effects of functions and have Typescript check against these descriptions. Google Closure seems to use this type of documentation for optimization. It could result in better self documenting code, more helpful tooling, and more logic errors caught.

I am fairly new to TypeScript so I'm not sure if this would be really helpful in practice or not. What do you think?

No side effects

/** @nosideeffects */
function a(){
  let foo = "asdf";
  foo = "bar";
  return a
} //OK, only local variables are assigned to

/** @nosideeffects */
function b(){
  return SOME_GLOBAL;
} //OK, reads global state but does not modify it

/** @nosideeffects */
function b(){
  SOME_GLOBAL = "asdf";
} //ERROR, non local variable assigned to

/** @nosideeffects */
function c(bar: string){
  bar = "123"
  return bar
} //OK, non-reference type argument modified

/** @nosideeffects */
function d(bar: {a: string}){
  bar.a = "123"
} //ERROR, reference type argument modified

/** @nosideeffects */
function e(){
  const foo = a();
  return foo
} //OK, only @nosideeffects functions are called


function f(){
  return "foo"
}

/** @nosideeffects */
function g(){
  const foo = f();
  return foo
} //ERROR, cannot call a normal function from a @nosideeffects function

Modifies

function a(){
  let myObj = {foo: {bar: "bar"}}
  b(myObj)
  console.log(foo.bar) //WARN: myObj may have been clobbered by b(myObj)
}

/** @modifies {arg} */
function b(arg: any){
  delete arg.foo
}
@ghost
Copy link

ghost commented Oct 27, 2017

Looks like a duplicate of #17181

@ghost ghost added the Duplicate An existing issue was already created label Oct 27, 2017
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants