Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a TypeScript equivalent to C#'s attributes

In C# there is a syntax available to define attributes of a property.

[Required]
string personName

It describes that personName is required. We can get the attributes of a property in any given time via reflection.

I was wondering if TypeScript has some feature like that?

like image 518
Luka Šilje Avatar asked Oct 07 '16 04:10

Luka Šilje


People also ask

Is there struct in TypeScript?

TypeScript is a Structural Type System. A structural type system means that when comparing types, TypeScript only takes into account the members on the type. This is in contrast to nominal type systems, where you could create two types but could not assign them to each other.

What is ?: In TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do you type in TypeScript?

We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon. TypeScript includes all the primitive types of JavaScript- number, string and boolean. In the above example, each variable is declared with their data type.


1 Answers

I was wondering if TypeScript has some feature like that?

Decorators are like that. E.g. mobx (https://github.com/mobxjs/mobx) uses it to make things observable.

class TodoList {
    @observable todos = [];
    @computed get unfinishedTodoCount() {
        return this.todos.filter(todo => !todo.finished).length;
    }
}
like image 180
basarat Avatar answered Oct 26 '22 00:10

basarat