TypeScript interface type checking from the beginning tutorial - interface

I've just started learning TypeScript and I'm having a hard time wrapping my head around an interface behavior from the beginning tutorial on http://www.typescriptlang.org/Playground/#tut=ex5
As I understand it, the interface should enforce the type of the parameters, however this particular line throws me off
var user = new Student("Jane", "M.", "User");
It compiles correctly and all is well, but when I modify it to
var user = new Student(1, 2, 3);
it also compiles just fine.
Could anyone elaborate why it's working ?
I understand that this is a beginners question but I could not find any info on this searching online and I don't have any TypeScript experts around me.
Thanks in advance,
Eugene

The type of the Student constructor parameters is any because there is no type annotation:
class Student {
fullname : string;
constructor(public firstname, public middleinitial, public lastname) {
this.fullname = firstname + " " + middleinitial + " " + lastname;
}
}
If we change it to have some type annotations, we'll get an error:
class Student {
fullname : string;
constructor(public firstname: string, // <-- add ': string' here
public middleinitial: string, // and here
public lastname: string) { // and here
this.fullname = firstname + " " + middleinitial + " " + lastname;
}
}
var x = new Student(1, 2, 3); // Error

Related

Variant type and non, with same name

i've tried to use typelite with entity framework and Identity framework.
in identity framework exists various types in the format TypeName<Tkey> and TypeName: TypeName<String>.
typelite correctly exports the types, but this behaviour is not possible in typescript, how should i work around that ?
Class:
namespace DTO
{
[TypeLite.TsClass]
public class Test : Test<String>
{
}
public class Test<TKey>
{
public TKey Id { get; set; }
public String Name { get; set; }
}
}
Configuration 1:
<# var ts = TypeScript.Definitions()
.WithReference("Enums.ts")
.ForLoadedAssemblies();
#>
Output 1, here the error is: Type 'Test<TKey>' recursively references itself as a base type.
declare module DTO {
interface Test extends DTO.Test<string> {
}
interface Test<TKey> {
Id: TKey;
Name: string;
}
}
Configuration 2:
<# var ts = TypeScript.Definitions()
.WithReference("Enums.ts")
.ForLoadedAssemblies()
.WithTypeFormatter((type, f) => "I" + ((TypeLite.TsModels.TsClass)type).Name);
#>
Output 2, here the variant Type got the I too and things got messed up badly
declare module DTO {
interface IUser {
Id: string;
Name: string;
Surname: string;
UserName: string;
Email: string;
Roles: string[];
}
interface ITest extends DTO.ITest {
}
interface ITest {
Id: ITKey;
Name: string;
}
}
If you have both generic and non-generic types with the same name, in the same namespace, you have to give them a slightly different name.
Change the model definition to:
var ts = TypeScript.Definitions()
.WithReference("Enums.ts")
.ForLoadedAssemblies();
ts.WithTypeFormatter((t, f) => GenerateTypeName(t, f, ts.ScriptGenerator));
Add this at the end:
<#+
private string GenerateTypeName(TsType tsType, ITsTypeFormatter f, TsGenerator gen)
{
TsClass tsClass = (TsClass) tsType;
string name = tsClass.Name;
if (!tsClass.GenericArguments.Any())
return name;
name += "_" + tsClass.GenericArguments.Count;
name += "<" + string.Join(",", tsClass.GenericArguments.Select(arg =>
{
string suffix = "";
var argCol = arg as TsCollection;
if (argCol != null)
{
suffix = string.Join("", Enumerable.Repeat("[]", argCol.Dimension));
}
return gen.GetFullyQualifiedTypeName(arg) + suffix;
})) + ">";
return name;
}
#>
It will generate:
declare module DTO {
interface ITest extends DTO.ITest_1<string> {
}
interface ITest_1<TKey> {
Id: TKey;
Value: string;
}
}

Why I can't access my script variable from class?

As topic says. I can't access variable from class made in same script.
It's in same script, and variables(as you see) are public. Any ideas?
Tried googling "how to access script variable from another class" but didn't found anything.
Code:
public var Ludnosc = new Array();
var humanCount : int;
public class Human {
public var id : byte;
public var creatureType = "HUMAN";
public var gender : boolean; // false = k, true = m
//public var firstname : String; <- Opcja do wprowadzenia później
//public var lastname : String; <- Opcja do wprowadzenia później
public var age : byte;
public var pregnant : boolean = false;
function Breed(partner) {
if(this.age<16) {
Debug.Log("Woman with id " + this.id + " is too young to be pregnant. She must be 16 or older.");
}
else {
var success = Random.Range(0.0, makePregnantChance);
Debug.Log("Breed chance of partners with IDs [" + this.id + ", " + partner + "] was " + success*100 + "%.");
if(success>0.50) {
this.pregnant = true;
Debug.Log("Creature of type " + this.creatureType + ", with ID " + this.id + " is pregnant!");
Ludnosc.push(new Human()); //LINE 44 | tworzymy nowego czlowieczka
var tempHuman = Ludnosc[humanCount+1] as Human //LINE 45
tempHuman.id = humanCount+1; //LINE 46
tempHuman.age = 1;
var losujPlec = Random.Range(0.0, 1.0);
tempHuman.makePregnantChance = 18/tempHuman.age;
}
}
}
public var parents : byte[]; //Najpierw podajemy ID matki, potem ID ojca.
public var makePregnantChance : float;
}
Bugs:
Assets/TextPierwszy.js(44,33): BCE0005: Unknown identifier: 'Ludnosc'.
Assets/TextPierwszy.js(45,49): BCE0005: Unknown identifier: 'Ludnosc'.
Assets/TextPierwszy.js(45,57): BCE0005: Unknown identifier: 'humanCount'.
Assets/TextPierwszy.js(46,48): BCE0005: Unknown identifier: 'humanCount'.
Your code here:
public var Ludnosc = new Array();
var humanCount : int;
public class Human {...
Needs to actually be:
public class Human {
public var Ludnosc = new Array();
var humanCount : int;
That is of course, if they're related to the class, if not, then you'll be better off creating another class to hold anything else HumanExtras (or something similar),for example.

Coffeescript Syntax Error

What's wrong here?
ExecJS::ProgramError: Error: Parse error on line 11: Unexpected '.'
.coffee
Person = Ember.Object.extend(
firstName: null
lastName: null
fullName: ->
firstName = #get("firstName")
lastName = #get("lastName")
firstName + " " + lastName
.property("firstName", "lastName")
)
Original .js
Person = Ember.Object.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: function() {
var firstName = this.get('firstName');
var lastName = this.get('lastName');
return firstName + ' ' + lastName;
}.property('firstName', 'lastName')
});
You need to add braces when you call the method.
Person = Ember.Object.extend(
firstName: null
lastName: null
fullName: (->
firstName = #get("firstName")
lastName = #get("lastName")
firstName + " " + lastName
).property("firstName", "lastName")
)
It is true that they are optional in Coffeescript, but in this situation I think you need to explicitly add them. At least it was the only way I could get it to compile. Perhaps a Coffeescript expert can enlighten as to why.

How to write a dynamic where 'like' query in Entity framework?

Here is my code:
//order my baselist is context.Entity
public static GridData Getdata<T>(ObjectSet<T> baseList,
int currentPage,
int rowsPerPage,
string sortcolumn,
string sortord,
string searchQuery,
string searchColumns)where T: class{
var query = baseList.OrderBy("it." + sortcolumn + " " + sortord);
string strPredicate = string.Empty;
if (!string.IsNullOrEmpty(searchColumns))
{
strPredicate = "it." + searchColumns + " LIKE #" + searchColumns + " ";
query = baseList.Where(strPredicate, new ObjectParameter(searchColumns, searchQuery)).OrderBy("it." + sortcolumn + " " + sortord);
}
}
My problem is i am trying to write down or form a like query in entity framework and seems like it does not support it.
You can use .Contains which is the LIKE operator equivalent in entity framework.
you can use this
query = baseList.Where(baseli=>baseli.Contains(searchColumns )).OrderBy("it." + sortcolumn + " " + sortord);
:)

Entity SQL Datetime Syntax error

Anyone know What is wrong with my syntax here? I am making dynamic eSQL Queries and running into an error when trying to make where condition for DateTime data type. This is the error:
The query syntax is not valid. Near term '2011', line 1, column 135.
If it matters the DateTime type in my entity is actually nullable DateTime?
However, I thought this is the correct syntax from everything I've read.
Here is the code:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>()
{
new EntityFilter<StudyFirstRead> { PropertyName = "username", OpType = ExpressionType.Equal, Value = "cwoodhouse" },
new EntityFilter<StudyFirstRead> { PropertyName = "FirstRead", OpType = ExpressionType.LessThan, Value = "DATETIME'2011-02-01 00:00'" }
};
Where EntityFilter is:
public class EntityFilter<T>
{
public string PropertyName { get; set; }
public ExpressionType OpType { get; set; }
public object Value { get; set; }
And I am building dynamic queries like so:
StringBuilder builder = new StringBuilder();
int counter = 0;
string baseStr = #"SELECT VALUE val FROM " + contextName + "." + tableName + " AS val WHERE val.";
builder.Append(baseStr);
foreach (EntityFilter<T> filter in filters)
{
//builder.Append(filter.PropertyName + " " + filter.OpTypeString() + " #p" + counter);
builder.Append(filter.PropertyName + " " + filter.OpTypeString() + "'" + filter.Value + "'");
counter++;
if (counter < filters.Count)
builder.Append(" AND val.");
else
{
break;
}
}
return builder.ToString();
It actually is the correct syntax for entity SQL (different than regular SQL or T-SQL).
Turns out the problem was too many single quotes, because I had them in both the EntityFilter object and the method that built the dynamic query.
according to you code the end of your SQL statement would produce something like
AND val.FirstRead = 'DATETIME'2011-02-01 00:00''
when executed you will get error
Error 102: Incorrect syntax near '2011'.
obviously that is not syntactically correct SQL, the quick fix whould be to have your filters collection as such:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>() {
new EntityFilter<StudyFirstRead> {
PropertyName = "username",
OpType = ExpressionType.Equal,
Value = "cwoodhouse"
}, new EntityFilter<StudyFirstRead> {
PropertyName = "FirstRead",
OpType = ExpressionType.LessThan,
Value = "2011-02-01 00:00"
}
};