I am pretty new to TypeScript. I started with a book called Typescript Revealed (Pub Feb.2013). In Chapter 2 there is a section called "Casts" that has the following example:
var a : int = <int>SomeNumberAsAString;
I tried to apply the example, as follows:
var SomeNumberAsAString = "1000";
var a: int = <int>SomeNumberAsAString;
But compiler gave me an error:
hello.ts(2,8): error TS2304: Cannot find name 'int'.
hello.ts(2,15): error TS2304: Cannot find name 'int'.
I'm wondering how to do this cast, or has the specification of Typescript changed?
(Pub Feb.2013)
That book is old. Its called number now.
var SomeNumberAsAString = "1000";
var a: number = <number><any>SomeNumberAsAString;
Also this assertion is very unsafe and I would not do this in production code. But it gets the point across :)
More
A more up to date book chapter on assertions : https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
https://basarat.gitbook.io/typescript/type-system/type-assertion
I've read #basarat's answer and decided to post my own since I strongly believe that there's still some room for explanation.
Be warned, <number><any> casting won't generate a number. In fact it will allow your code to be compiled (thus you'll pass all static typing checks) but it won't be a number in javascript. Consider this snippet of code:
let str = "1000";
let a: number = <number><any>str;
let b: number = parseInt(str); //or just let b = parseInt(str)
console.log(typeof a); // string
console.log(typeof b); // number
I hardly can imagine cases when a-case is beneficial compared to b-case. I'd go with just parseInt or parseFloat or Number, whatever fits more. <T><any> casting looks smart but you must be 100% sure what you are supposed to achieve by that idiom.
And in most cases you probably don't want to achieve that )
Here is the cleanest way to do it.
const numberString = '1000';
const a: int = numberString as any;
I prefer this variant
let SomeNumberAsAString = '1000';
let a = +SomeNumberAsAString;
console.log(a);
const a: number = <number> +SomeNumberAsAString;
+SomeNumberAsAString converts the string value to the number.
<number> before +SomeNumberAsAString says to Typescript compiler that we need to cast the type of the value to type number.
Related
I'm typing the following in my code
boost::numeric::interval<double> foo = ...;
double length = std::abs(foo.upper() - foo.lower());
It surprises me I can't find a simple utility in boost::numeric::interval that calculates the length. I'd expect a length function so that I can do
boost::numeric::interval<double> foo = ...;
double length = length(foo);
Is this either
missing from the library as an oversight
missing from the library for good reason as it doesn't fit the concept
there but under another name which I've failed to see
Obviously I can write a simple inline function to do this but I'm a bit surprised that I have to given that I see functions like min and max
I just found it after I posted the question
Answer is "width"
boost::numeric::interval<double> foo = ...;
double length = width(foo);
I'm writing a library in TypeScript, and I want to check that my type definitions are correct. Often, I want to check that a variable has a certain static type. I usually do it like this:
let expectedToBeString : string = Api.callFunction("param1", 2, []);
But sometimes, a type might be widened to any without me knowing about it, so the above expression would still compile. So I'd want to make sure it's not any by writing an expression that will intentionally fail type checking.
Sometimes I also want to check that my set of overloads works for legal types, but not for illegal ones, but the only way to make sure of that is to raise a compilation error.
How can I verify that a compilation error is being raised when it should be?
Interesting issue. When conditional types are released in TypeScript v2.8, coming out supposedly sometime this month (March 2018), or available now at typescript#next, you will be able to do something like this:
type ReplaceAny<T, R> = 0 extends (1 & T) ? R : T
The ReplaceAny<T, R> type will be T unless T is any, in which case it will be R. No normal type T should satisfy 0 extends (1 & T), since 1 & T should be at least as narrow as 1, and 0 is not a subtype of 1. But the any type in TypeScript breaks the rules: it's considered to be both a supertype of and a subtype of every other type (more or less). Which means that 1 & any becomes any, and 0 extends any is true. So 0 extends (1 & T) behaves like an any detector.
Now we can make a convenience function like this:
const replaceAny = <R>() => <T>(x: T): ReplaceAny<T,R> => x as any;
If you call replaceAny<{}>(), it produces a function which will take any input and return a value of type {} if that input is of type any.
So let's examine some scenarios:
declare const Api: {
callFunctionS(...args: any[]): string,
callFunctionN(...args: any[]): number,
callFunctionA(...args: any[]): any,
}
let expectedToBeString: string;
expectedToBeString =
replaceAny<{}>()(Api.callFunctionS("param1", 2, []));
// okay
expectedToBeString =
replaceAny<{}>()(Api.callFunctionN("param1", 2, []));
// error, number not assignable to string
expectedToBeString =
replaceAny<{}>()(Api.callFunctionA("param1", 2, []));
// error, {} not assignable to string
The first two behave as you expect, where expectedToBeString is happy with callFunctionS() but angry about callFunctionN(). The new behavior is that it is also angry about callFunctionA(), since replaceAny<{}>() causes the return value to be of type {} instead of any, and {} is not assignable to string.
Hope that helps; good luck!
I was coding with a beginner C++ group and we were creating a 'Car' class. Someone suggested 'tyre type' as a possible variable/attribute to the class as a boolean type. Another person then asked whether booleans should be directly answerable with a yes/no.
I was just wondering the same. How do you best manage a variable this and how do you later specify two options, such as winter/summer, for this variable?
Well, it depends.
Your goal is to write clear, readable, maintainable, and correct code. It's not so much that bool necessitates a yes vs. no answer as much as it is a question of whether or not using boolean (or any other type for that matter) helps you to meet these goals. If it makes your code clear, it's worth considering. If it makes things confusing, it's not a good idea.
For example, you may only have two types of tires, but consider a couple of things:
How do you know you won't add more later? You don't want to shoot yourself in the foot.
When writing / reading the code how do you remember that true is "summer" and false is "winter"? Will you have to maintain that info in your head / always look it up somewhere? Will it be easy to make a mistake? Will it confuse a reader who is unfamiliar with your code?
Think about those kinds of things. In your case, while using a boolean will certainly get the job done, I'd say it's a good use for an enum, even if you only have two values right now (or ever). E.g.:
enum TireType { WinterTire, SummerTire };
Now everything falls into place:
You can add new types in the future if you'd like, with no major issues.
A variable TireType t documents itself, we know just at a glance that t is a tire type.
There is much less of a chance of mistake when entering values: It'll be very hard to confuse WinterTire with SummerTire, whereas true and false discard all semantic meaning.
A boolean has two options, but those options are "true" or "false" (or, occasionally, "yes" and "no").
We do not generally represent other variables with two options as booleans.
If you have tyre types (of which there currently so happen to be two), I would suggest enums for this.
As always, there are exceptions. If your tyre types are "tyre with oil on it" and "tyre without oil on it", then you could use a boolean called tyreHasOilOnIt.
Really, it is up to you.
A boolean type is generally a value with precisely two values, one being truthy and the other falsy. This can to some degree be bent to other meanings. In your case when I saw discussion of tyre type I had no idea what the two values would mean untill reading the comments.
In my opinion when the value isn't self explanatory like this I would not use a boolean.
In your case, if the types of tyre are known at the time you write the program I would use an enum of some sort, and if they are not known just a plain string.
I would suggest don't use either enum or bool type for tyre type as a possible variable/attribute may change as you specified yes/no or Winter/Summer . Its better to use it as short int which values you can track or map with respect to yes,no,winter,summer . This will allow you to assign or change as per your need and class will never need a change.
Example :
Class car
{
// we will use tyre type to map enum
//type and other type if required
int tyreType;
};
enum tyre_type_t
{
//default value is considered 100
// since we can use previous
//value any other purpose.
WINTER = 100,
SUMMER
}
int main()
{
Car obj;
obj.tyreType = 1; // Yes
obj.tyreType = 0; // No
obj.tyreType = WINTER;
// Now we can assig enum.
// values //too.
return 0;
}
Happy Coding
Example :
Class car
{
// we will use tyre type to map enum
//type and other type if required
int tyreType;
};
enum tyre_type_t
{
//default value is considered 100
// since we can use previous
//value any other purpose.
WINTER = 100,
SUMMER
}
int main()
{
Car obj;
obj.tyreType = 1; // Yes
obj.tyreType = 0; // No
obj.tyreType = WINTER;
// Now we can assig enum.
// values //too.
return 0;
}
Happy Coding
I am trying to write a halstead complexity measure in X++ (language isn't important) and I think the best way of doing this is by using regex on the source.
I have managed to do 90% of it but am struggling on variable names.
How do I identify a variable name in a piece of code.
Given the following piece of code
public void main()
{
int a, b, c, av;
className class;
strFmt("%1 %2 %3", a, b, c);
av = (a + b + c) / 3;
info("avg = %1");*/
if(a)
{
a++;
class.add(a);
}
else
{
b++;
class.subtract(b)
}
this.main();
}
I expect to be returned "a" "b" "c" "av" "class"
With the halstead it needs to count the instances of them. The way I was thinking is by storing the above in a list and then using whatever is in the list in a regex query. Catering for all possible uses of a variable would be insane.
I think you would have to reflect on the AOT in order to get the different variables.
You could use reflection with TreeNode or maybe you could use the XPPCompiler to get info on the objects you're processing to help:
info(strFmt("%1", new xppCompiler().dumpClass('salesformletter')));
This question made me sort of curious about how to do this and I came across this great post that has a custom AX tool to measure complexity plus a 175 page grad paper written about it.
http://bojanjovicic.com/complexity-tool-dynamics-ax-2009/
I'm experimenting with it now and looking how I can build onto it.
I'm back with the actual answer! Use the SysScannerClass and TreeNode object to correctly parse the code. Here's a beautiful sample I wrote that should make it cake.
static void JobParseSourceCode(Args _args)
{
TreeNode treeNode = TreeNode::findNode(#'\Data Dictionary\Tables\SalesTable\Methods\find');
SysScannerClass sysScannerClass = new SysScannerClass(treeNode);
int symbol;
int curLine;
str lineStr;
setPrefix("Scanning " + treeNode.treeNodePath());
for (symbol = sysScannerClass.firstSymbol(); symbol; symbol = sysScannerClass.nextSymbol())
{
if (curLine != sysScannerClass.line())
{
curLine = sysScannerClass.line();
lineStr = sysScannerClass.sourceLine(curLine);
}
// NOTE: symbol corresponds to macros in #TokenTypes
info(strFmt("Line %1: %2\t(Col %3): '%4' - MacroValue: %5, [%6]", curLine, lineStr, sysScannerClass.col(), sysScannerClass.strValue(), symbol, xppScanner::symbolClass(symbol)));
}
}
Well, the example does not quite qualify as X++ source, because class is a reserved word and cannot be used for a variable name.
Besides that a crude search for [a-zA-Z_][a-zA-Z_0-9]+ would give you all strings which could be a variable name. But without a full parser you would have trouble determining whether it is a keyword, class name, table name et cetera or a genuine variable name.
You could also use TextBuffer to tokenize your source:
static void TokenTest(Args _args)
{
str src = #'
public void main()
{
int a = 7, b = 11, c = 13, av;
info(strFmt("%1 %2 %3", a, b, c));
av = (a + b + c) / 3;
info(strFmt("avg = %1"));
this.main();
}
';
TextBuffer t = new TextBuffer();
t.ignoreCase(true);
t.setText(src); // Set the text to break in to tokens
while (t.nextToken(false,' (){}.,:;!=+-*/\n')) // The delimiters to search
{
info(t.token());
}
}
This will not work with strings and comments of course.
There is even an undocumented Keywords kernel class to play with!
Maybe the best choice would be to integrate with the cross reference tool, it has done the splitting for you!
I am afraid your remaining 10% may take 90% of your time!
You can use regex101.com to play with regex. I think you can play with the look-ahead (?=...) and the look-behind(?<=...) groups:
This regex will match all your variables:
/(?!void)(?<=[ \(])[a-z]+(?=[, ;+*\/\)])/
And here the proof:
http://regex101.com/r/hS9dQ6/2
I ended up cheating with the solution. I had already got all of the operators information such as int/public/methods etc... so I just used substituion on the source and then ran the following regex which found me the operands for the metric.
'_?\w+(?=([^"]*"[^"]*")*[^"]*$)|".+"'
There were some really good answers on here so I am going to look into using a hybrid of them to improve the implementation at a later date but for now we are getting the information we need and it seems to work for all cases we have tested it on.
If anyone is interested the regex I used for the operators is the following
(?i)\(|\{|\w+(?=(\(|:|\.))|\w+(?=\s\w)|(break|continue|return|true|false|retry|asc|breakpoint|desc|null|pause|throw|ttsAbort|ttsBegin|ttsCommit)(?=;)|((try|catch|else|by|do)(?=\n))|(\+=|-=|>=|<=|==|!=|=|\+\+|--|<<|>>|&&|\|\||\*|\/|\+|-|~|&|\^|\||>|<|!|\?|::|:|\.)+(?=([^"]*"[^"]*")*[^"]*$)
It has all the reserved keywords which are not covered by the first 4 statements, I also got the list of operators which x++ use.
It will need some modification to be used in other languages but considering other languages have better ways of dealing with these things you probably don't need it.
Thanks for all your answers
I noticed for a while now the following syntax in some of our code:
if( NULL == var){
//...
}
or
if( 0 == var){
//...
}
and similar things.
Can someone please explain why did the person who wrote this choose this notation instead of the common var == 0 way)?
Is it a matter of style, or does it somehow affect performance?
It's a mechanism to avoid mistakes like this:
if ( var = NULL ) {
// ...
}
If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes:
if ( NULL = var ) { // not legal, won't compile
// ...
}
Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing.
Edit:
As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, gcc -Wall will give you the following:
warning: suggest parentheses around assignment used as truth value
You should always enable warnings on your compiler, it is the cheapest way to find errors.
Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.
If you mistakenly put
if ( var = NULL )
instead of
if ( var == NULL )
then there will only be a compiler warning. If you reverse the order:
if ( NULL == var )
then there will be a compiler error if you put
if ( NULL = var )
Personally, I hate to read code written that way, and I only made that mistake once in my first year of coding. =)
To avoid the
if (var = NULL)
bug
Corollary: try to use const as much as you can.
const int val = 42;
if (val = 43) {
...
}
will not compile.
Quoting Joel On Software, The Guerrilla Guide to Interviewing:
Occasionally, you will see a C programmer write something like if (0==strlen(x)), putting the constant on the left hand side of the == . This is a really good sign. It means that they were stung once too many times by confusing = and == and have forced themselves to learn a new habit to avoid that trap.
(I'm not really a fan of this "best practice".)
Just by the way, I've observed over many years teaching C to new programmers that if you train yourself to read "=" as "gets" and "==" as equals, that in itself will save you from a lot of these bugs. Then you read
if( x = 0){
as "if x gets 0 then" and that begins to sound weird.
Personally, I prefer
if (!x) {