mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 09:41:36 +00:00
- fix merge swift conflict
- Merge master
This commit is contained in:
commit
313c0daf05
@ -73,9 +73,9 @@ echo Hello, $NAME!
|
||||
# use 'man test' for more info about conditionals
|
||||
if [ $NAME -ne $USER ]
|
||||
then
|
||||
echo "Your name is your username"
|
||||
else
|
||||
echo "Your name isn't your username"
|
||||
else
|
||||
echo "Your name is your username"
|
||||
fi
|
||||
|
||||
# There is also conditional execution
|
||||
|
@ -7,23 +7,24 @@ contributors:
|
||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||
translators:
|
||||
- ["Francisco Gomez", "http://github.com/frncscgmz"]
|
||||
- ["Joaquín Ferrero", "http://github.com/joaquinferrero"]
|
||||
lang: es-es
|
||||
---
|
||||
|
||||
Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo.
|
||||
Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
|
||||
|
||||
Perl 5 corre en mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala.
|
||||
Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
|
||||
|
||||
```perl
|
||||
# Comentarios de una sola linea con un carácter hash.
|
||||
# Comentarios de una sola línea con un carácter hash
|
||||
|
||||
#### Tipos de variables en Perl
|
||||
|
||||
# Las variables comienzan con el símbolo $.
|
||||
# Un nombre de variable valido empieza con una letra o un guión bajo,
|
||||
# seguido por cualquier numero de letras, números o guiones bajos.
|
||||
# Las variables comienzan con el símbolo $
|
||||
# Un nombre de variable válido empieza con una letra o un guión bajo,
|
||||
# seguido por cualquier número de letras, números o guiones bajos
|
||||
|
||||
### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes.
|
||||
### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes
|
||||
|
||||
## Escalares
|
||||
# Un escalar representa un solo valor:
|
||||
@ -31,99 +32,98 @@ my $animal = "camello";
|
||||
my $respuesta = 42;
|
||||
|
||||
# Los valores escalares pueden ser cadenas de caracteres, números enteros o
|
||||
# de punto flotante, Perl automáticamente los convertirá como sea requerido.
|
||||
# de punto flotante; Perl automáticamente los convertirá como sea requerido
|
||||
|
||||
## Arreglos
|
||||
# Un arreglo representa una lista de valores:
|
||||
my @animales = {"camello","llama","buho"};
|
||||
my @numeros = {23,42,69};
|
||||
my @mixto = {"camello",42,1.23};
|
||||
|
||||
|
||||
my @animales = ("camello","llama","buho"};
|
||||
my @numeros = (23, 42, 69);
|
||||
my @mixto = ("camello", 42, 1.23);
|
||||
|
||||
## Hashes
|
||||
# Un hash representa un conjunto de pares llave/valor:
|
||||
|
||||
my %color_fruta = {"manzana","rojo","banana","amarillo"};
|
||||
|
||||
# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas
|
||||
# fácilmente.
|
||||
# Un hash representa un conjunto de pares llave/valor:
|
||||
my %color_fruta = ("manzana","rojo","banana","amarillo");
|
||||
|
||||
# Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente
|
||||
my %color_fruta = (
|
||||
manzana => "rojo",
|
||||
banana => "amarillo",
|
||||
);
|
||||
# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata).
|
||||
);
|
||||
|
||||
# Los tipos de datos mas complejos pueden ser construidos utilizando
|
||||
# referencias, las cuales te permiten construir listas y hashes dentro
|
||||
# de listas y hashes.
|
||||
# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata)
|
||||
|
||||
# Los tipos de datos más complejos se pueden construir utilizando
|
||||
# referencias, las cuales le permiten construir listas y hashes dentro
|
||||
# de listas y hashes
|
||||
|
||||
#### Estructuras condicionales y de ciclos
|
||||
|
||||
# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes.
|
||||
|
||||
# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
|
||||
if ( $var ) {
|
||||
...
|
||||
...;
|
||||
} elsif ( $var eq 'bar' ) {
|
||||
...
|
||||
...;
|
||||
} else {
|
||||
...
|
||||
...;
|
||||
}
|
||||
|
||||
unless ( condicion ) {
|
||||
...
|
||||
}
|
||||
# Esto es proporcionado como una version mas fácil de leer que "if (!condición)"
|
||||
...;
|
||||
}
|
||||
|
||||
# La post condición al modo Perl
|
||||
# Esto se ofrece como una versión más fácil de leer que "if (!condición)"
|
||||
|
||||
# La postcondición al modo Perl:
|
||||
print "Yow!" if $zippy;
|
||||
print "No tenemos bananas" unless $bananas;
|
||||
|
||||
# while
|
||||
while ( condicion ) {
|
||||
...
|
||||
}
|
||||
|
||||
while ( condicion ) {
|
||||
...;
|
||||
}
|
||||
|
||||
# for y foreach
|
||||
for ($i = 0; $i <= $max; $i++) {
|
||||
...
|
||||
}
|
||||
...;
|
||||
}
|
||||
|
||||
for $i (0 .. $max) {
|
||||
...;
|
||||
}
|
||||
|
||||
foreach (@array) {
|
||||
print "Este elemento es $_\n";
|
||||
}
|
||||
print "Este elemento es $_\n";
|
||||
}
|
||||
|
||||
|
||||
#### Expresiones regulares
|
||||
|
||||
# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es
|
||||
# sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
|
||||
# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
|
||||
# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
|
||||
# Sin embargo, resumiendo:
|
||||
|
||||
# Pareo simple
|
||||
# Coincidencia simple
|
||||
if (/foo/) { ... } # verdadero si $_ contiene "foo"
|
||||
if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo"
|
||||
|
||||
# Substitución simple
|
||||
$a =~ s/foo/bar/; # remplaza foo con bar en $a
|
||||
$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a
|
||||
$a =~ s/foo/bar/; # remplaza "foo" con "bar" en $a
|
||||
$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en $a
|
||||
|
||||
|
||||
#### Archivos e I/O
|
||||
#### Archivos y E/S
|
||||
|
||||
# Puedes abrir un archivo para obtener datos o escribirlos utilizando la
|
||||
# función "open()".
|
||||
# Puede abrir un archivo para obtener datos o escribirlos utilizando la
|
||||
# función "open()"
|
||||
|
||||
open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!";
|
||||
open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!";
|
||||
open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!";
|
||||
|
||||
# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>"
|
||||
# operador. En contexto escalar leer una sola linea desde el gestor de
|
||||
# archivo, y en contexto de lista leer el archivo completo en donde, asigna
|
||||
# cada linea a un elemento de la lista.
|
||||
# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>".
|
||||
# En contexto escalar, leer una sola línea desde el gestor de archivo, y
|
||||
# en contexto de lista, leer el archivo completo en donde asigna
|
||||
# cada línea a un elemento de la lista
|
||||
|
||||
my $linea = <$entrada>;
|
||||
my @lineas = <$entrada>;
|
||||
@ -131,30 +131,26 @@ my @lineas = <$entrada>;
|
||||
#### Escribiendo subrutinas
|
||||
|
||||
# Escribir subrutinas es fácil:
|
||||
|
||||
sub logger {
|
||||
my $mensajelog = shift;
|
||||
open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!";
|
||||
print $archivolog $mensajelog;
|
||||
}
|
||||
|
||||
# Ahora podemos utilizar la subrutina al igual que cualquier otra función
|
||||
# incorporada:
|
||||
|
||||
# Ahora podemos utilizar la subrutina al igual que cualquier otra función incorporada:
|
||||
logger("Tenemos una subrutina logger!");
|
||||
|
||||
|
||||
```
|
||||
|
||||
#### Utilizando módulos Perl
|
||||
|
||||
Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl.
|
||||
Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl.
|
||||
|
||||
perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar.
|
||||
perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar.
|
||||
|
||||
#### Material de Lectura
|
||||
|
||||
- [perl-tutorial](http://perl-tutorial.org/)
|
||||
- [Aprende en www.perl.com](http://www.perl.org/learn.html)
|
||||
- [Learn Perl](http://www.perl.org/learn.html)
|
||||
- [perldoc](http://perldoc.perl.org/)
|
||||
- y perl incorporado: `perldoc perlintro`
|
||||
- y en su propio perl: `perldoc perlintro`
|
||||
|
@ -101,7 +101,7 @@ public class LearnJava {
|
||||
|
||||
// Arrays
|
||||
//The array size must be decided upon instantiation
|
||||
//The following formats work for declaring an arrow
|
||||
//The following formats work for declaring an array
|
||||
//<datatype> [] <var name> = new <datatype>[<array size>];
|
||||
//<datatype> <var name>[] = new <datatype>[<array size>];
|
||||
int [] intArray = new int[10];
|
||||
|
@ -488,6 +488,7 @@ sub truthy-array(@array) {
|
||||
# (it'll stop at the furthest operator in the current expression)
|
||||
my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }`
|
||||
my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }`
|
||||
# also `sub ($a, $b) { $a + $b + 3 }`
|
||||
say (*/2)(4); #=> 2
|
||||
# Immediatly execute the function Whatever created.
|
||||
say ((*+3)/5)(5); #=> 1.6
|
||||
@ -496,7 +497,8 @@ say ((*+3)/5)(5); #=> 1.6
|
||||
# But if you need to have more than one argument (`$_`)
|
||||
# in a block (without wanting to resort to `-> {}`),
|
||||
# you can also use the implicit argument syntax, `$^` :
|
||||
map({ $^a + $^b + 3 }, @array); # same as the above
|
||||
map({ $^a + $^b + 3 }, @array); # equivalent to following:
|
||||
map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)
|
||||
|
||||
# Note : those are sorted lexicographically.
|
||||
# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }`
|
||||
@ -1072,6 +1074,11 @@ my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above)
|
||||
my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers,
|
||||
# computed using a closure!
|
||||
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above)
|
||||
my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above)
|
||||
# $a and $b will always take the previous values, meaning here
|
||||
# they'll start with $a = 1 and $b = 1 (values we set by hand).
|
||||
# then $a = 1 and $b = 2 (result from previous $a+$b), and so on.
|
||||
|
||||
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
|
||||
# (using a range as the index)
|
||||
# Note : as for ranges, once reified, elements aren't re-calculated.
|
||||
|
195
purescript.html.markdown
Normal file
195
purescript.html.markdown
Normal file
@ -0,0 +1,195 @@
|
||||
---
|
||||
language: purescript
|
||||
contributors:
|
||||
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
|
||||
---
|
||||
|
||||
PureScript is a small strongly, statically typed language compiling to Javascript.
|
||||
|
||||
* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
|
||||
* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/)
|
||||
* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
|
||||
|
||||
```haskell
|
||||
|
||||
--
|
||||
-- 1. Primitive datatypes that corresponds to their Javascript
|
||||
-- equivalents at runtime.
|
||||
|
||||
-- Numbers
|
||||
1 + 7*5 :: Number -- 36
|
||||
-- Types are inferred, so the following works fine
|
||||
9 / 2.5 + 4.4 -- 8
|
||||
-- Hexadecimal literals
|
||||
0xff + 1 -- 256
|
||||
-- Unary negation
|
||||
6 * -3 -- -18
|
||||
6 * negate 3 -- -18
|
||||
-- Modulus
|
||||
3 % 2 -- 1
|
||||
4 % 2 -- 0
|
||||
-- Inspect the type of an expression in psci
|
||||
:t 9 / 2.5 + 4.4 -- Prim.Number
|
||||
|
||||
-- Booleans
|
||||
true :: Boolean -- true
|
||||
false :: Boolean -- false
|
||||
-- Negation
|
||||
not true --false
|
||||
23 == 23 -- true
|
||||
1 /= 4 -- true
|
||||
1 >= 4 -- false
|
||||
-- Comparisions < <= > >=
|
||||
-- are defined in terms of compare
|
||||
compare 1 2 -- LT
|
||||
compare 2 2 -- EQ
|
||||
compare 3 2 -- GT
|
||||
-- Conjunction and Disjunction
|
||||
true && (9 >= 19 || 1 < 2) -- true
|
||||
|
||||
-- Strings
|
||||
"Hellow" :: String -- "Hellow"
|
||||
-- Multiline string
|
||||
"Hellow\
|
||||
\orld" -- "Helloworld"
|
||||
-- Concatenate
|
||||
"such " ++ "amaze" -- "such amaze"
|
||||
|
||||
--
|
||||
-- 2. Arrays are Javascript arrays, but must be homogeneous
|
||||
|
||||
[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8]
|
||||
[true, true, false] :: [Boolean] -- [true,true,false]
|
||||
-- [1,2, true, "false"] won't work
|
||||
-- `Cannot unify Prim.Number with Prim.Boolean`
|
||||
-- Cons (prepend)
|
||||
1 : [2,4,3] -- [1,2,4,3]
|
||||
|
||||
-- Requires purescript-arrays (Data.Array)
|
||||
-- and purescript-maybe (Data.Maybe)
|
||||
|
||||
-- Safe access return Maybe a
|
||||
head [1,2,3] -- Just (1)
|
||||
tail [3,2,1] -- Just ([2,1])
|
||||
init [1,2,3] -- Just ([1,2])
|
||||
last [3,2,1] -- Just (1)
|
||||
-- Random access - indexing
|
||||
[3,4,5,6,7] !! 2 -- Just (5)
|
||||
-- Range
|
||||
1..5 -- [1,2,3,4,5]
|
||||
length [2,2,2] -- 3
|
||||
drop 3 [5,4,3,2,1] -- [2,1]
|
||||
take 3 [5,4,3,2,1] -- [5,4,3]
|
||||
append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
|
||||
|
||||
--
|
||||
-- 3. Records are Javascript objects, with zero or more fields, which
|
||||
-- can have different types
|
||||
let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
|
||||
-- Access properties
|
||||
book.title -- "Foucault's pendulum"
|
||||
|
||||
getTitle b = b.title
|
||||
-- Works on all records with a title (but doesn't require any other field)
|
||||
getTitle book -- "Foucault's pendulum"
|
||||
getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
|
||||
-- Update a record
|
||||
changeTitle b t = b {title = t}
|
||||
changeTitle book "Ill nome della rosa" -- {title: "Ill nome della
|
||||
-- rosa", author: "Umberto Eco"}
|
||||
|
||||
--
|
||||
-- 4. Functions
|
||||
sumOfSquares x y = x*x+y*y
|
||||
sumOfSquares 3 4 -- 25
|
||||
-- In psci you have to write `let` in front of the function to get a
|
||||
-- top level binding
|
||||
mod x y = x % y
|
||||
mod 3 2 -- 1
|
||||
-- Infix application of function
|
||||
3 `mod` 2 -- 1
|
||||
|
||||
-- function application have higher precedence than all other
|
||||
-- operators
|
||||
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
|
||||
|
||||
-- Conditional
|
||||
abs' n = if n>=0 then n else -n
|
||||
abs' (-3) -- 3
|
||||
|
||||
-- Guarded equations
|
||||
abs n | n >= 0 = n
|
||||
| otherwise = -n
|
||||
|
||||
-- Pattern matching
|
||||
|
||||
-- Note the type signature, input is an array of numbers The pattern
|
||||
-- matching destructures and binds the array into parts
|
||||
first :: [Number] -> Number
|
||||
first (x:_) = x
|
||||
first [3,4,5] -- 3
|
||||
second :: [Number] -> Number
|
||||
second (_:y:_) = y
|
||||
second [3,4,5] -- 4
|
||||
sumTwo :: [Number] -> [Number]
|
||||
sumTwo (x:y:rest) = (x+y) : rest
|
||||
sumTwo [2,3,4,5,6] -- [5,4,5,6]
|
||||
|
||||
-- sumTwo doesn't handle when the array is empty or just have one
|
||||
-- element in which case you get an error
|
||||
sumTwo [1] -- Failed pattern match
|
||||
|
||||
-- Complementing patterns to match
|
||||
-- Good ol' Fibonacci
|
||||
fib 1 = 1
|
||||
fib 2 = 2
|
||||
fib x = fib (x-1) + fib (x-2)
|
||||
fib 10 -- 89
|
||||
|
||||
-- Use underscore to match any, where you don't care about the binding name
|
||||
isZero 0 = true
|
||||
isZero _ = false
|
||||
|
||||
-- Pattern matching on records
|
||||
ecoTitle {author = "Umberto Eco", title = t} = Just t
|
||||
ecoTitle _ = Nothing
|
||||
|
||||
ecoTitle book -- Just ("Foucault's pendulum")
|
||||
ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
|
||||
-- ecoTitle requires both field to type check:
|
||||
ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
|
||||
|
||||
-- Lambda expressions
|
||||
(\x -> x*x) 3 -- 9
|
||||
(\x y -> x*x + y*y) 4 5 -- 41
|
||||
sqr = \x -> x*x
|
||||
|
||||
-- Currying
|
||||
add x y = x + y -- is equivalent with
|
||||
add = \x -> (\y -> x+y)
|
||||
add3 = add 3
|
||||
:t add3 -- Prim.Number -> Prim.Number
|
||||
|
||||
-- Forward and backward function composition
|
||||
-- drop 3 followed by taking 5
|
||||
(drop 3 >>> take 5) (1..20) -- [4,5,6,7,8]
|
||||
-- take 5 followed by dropping 3
|
||||
(drop 3 <<< take 5) (1..20) -- [4,5]
|
||||
|
||||
-- Operations using higher order functions
|
||||
even x = x % 2 == 0
|
||||
filter even (1..10) -- [2,4,6,8,10]
|
||||
map (\x -> x+11) (1..5) -- [12,13,14,15,16]
|
||||
|
||||
-- Requires purescript-foldable-traversabe (Data.Foldable)
|
||||
|
||||
foldr (+) 0 (1..10) -- 55
|
||||
sum (1..10) -- 55
|
||||
product (1..10) -- 3628800
|
||||
|
||||
-- Testing with predicate
|
||||
any even [1,2,3] -- true
|
||||
all even [1,2,3] -- false
|
||||
|
||||
```
|
||||
|
@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense -
|
||||
|
||||
// A do while loop
|
||||
do {
|
||||
println("x is still less then 10");
|
||||
println("x is still less than 10");
|
||||
x += 1
|
||||
} while (x < 10)
|
||||
|
||||
|
@ -60,7 +60,7 @@ var occupations = [
|
||||
"kaylee": "Mechanic"
|
||||
]
|
||||
occupations["Jayne"] = "Public Relations"
|
||||
let emptyDictionary = Dictionary<String, Float>()
|
||||
let emptyDictionary = [String: Float]()
|
||||
|
||||
|
||||
//
|
||||
@ -226,7 +226,6 @@ public class Shape {
|
||||
// If you just need to store data in a
|
||||
// structured object, you should use a `struct`
|
||||
|
||||
// A simple class `Square` extends `Shape`
|
||||
internal class Rect: Shape {
|
||||
var sideLength: Int = 1
|
||||
|
||||
@ -271,6 +270,7 @@ internal class Rect: Shape {
|
||||
}
|
||||
}
|
||||
|
||||
// A simple class `Square` extends `Rect`
|
||||
class Square: Rect {
|
||||
convenience init() {
|
||||
self.init(sideLength: 5)
|
||||
|
158
typescript.html.markdown
Normal file
158
typescript.html.markdown
Normal file
@ -0,0 +1,158 @@
|
||||
---
|
||||
language: TypeScript
|
||||
contributors:
|
||||
- ["Philippe Vlérick", "https://github.com/pvlerick"]
|
||||
filename: learntypescript.ts
|
||||
---
|
||||
|
||||
TypeScript is a language that aims at easing development of large scale applications written in JavaScript.
|
||||
TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript.
|
||||
It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript.
|
||||
|
||||
This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/).
|
||||
|
||||
To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript.
|
||||
|
||||
```ts
|
||||
//There are 3 basic types in TypeScript
|
||||
var isDone: boolean = false;
|
||||
var lines: number = 42;
|
||||
var name: string = "Anders";
|
||||
|
||||
//..When it's impossible to know, there is the "Any" type
|
||||
var notSure: any = 4;
|
||||
notSure = "maybe a string instead";
|
||||
notSure = false; // okay, definitely a boolean
|
||||
|
||||
//For collections, there are typed arrays and generic arrays
|
||||
var list: number[] = [1, 2, 3];
|
||||
//Alternatively, using the generic array type
|
||||
var list: Array<number> = [1, 2, 3];
|
||||
|
||||
//For enumerations:
|
||||
enum Color {Red, Green, Blue};
|
||||
var c: Color = Color.Green;
|
||||
|
||||
//Lastly, "void" is used in the special case of a function not returning anything
|
||||
function bigHorribleAlert(): void {
|
||||
alert("I'm a little annoying box!");
|
||||
}
|
||||
|
||||
//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference
|
||||
//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted
|
||||
var f1 = function(i: number) : number { return i * i; }
|
||||
var f2 = function(i: number) { return i * i; } //Return type infered
|
||||
var f3 = (i : number) : number => { return i * i; }
|
||||
var f4 = (i: number) => { return i * i; } //Return type infered
|
||||
var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed
|
||||
|
||||
//Interfaces are structural, anything that has the properties is compliant with the interface
|
||||
interface Person {
|
||||
name: string;
|
||||
//Optional properties, marked with a "?"
|
||||
age?: number;
|
||||
//And of course functions
|
||||
move(): void;
|
||||
}
|
||||
|
||||
//..Object that implements the "Person" interface
|
||||
var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties
|
||||
//..Objects that have the optional property:
|
||||
var validPerson : Person = { name: "Bobby", age: 42, move: () => {} };
|
||||
var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number
|
||||
|
||||
//..Interfaces can also describe a function type
|
||||
interface SearchFunc {
|
||||
(source: string, subString: string): boolean;
|
||||
}
|
||||
//..Only the parameters' types are important, names are not important.
|
||||
var mySearch: SearchFunc;
|
||||
mySearch = function(src: string, sub: string) {
|
||||
return src.search(sub) != -1;
|
||||
}
|
||||
|
||||
//Classes - members are public by default
|
||||
class Point {
|
||||
//Properties
|
||||
x: number;
|
||||
|
||||
//Constructor - the public/private keywords in this context will generate the boiler plate code
|
||||
// for the property and the initialization in the constructor.
|
||||
// In this example, "y" will be defined just like "x" is, but with less code
|
||||
//Default values are also supported
|
||||
constructor(x: number, public y: number = 0) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
//Functions
|
||||
dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
||||
|
||||
//Static members
|
||||
static origin = new Point(0, 0);
|
||||
}
|
||||
|
||||
var p1 = new Point(10 ,20);
|
||||
var p2 = new Point(25); //y will be 0
|
||||
|
||||
//Inheritance
|
||||
class Point3D extends Point {
|
||||
constructor(x: number, y: number, public z: number = 0) {
|
||||
super(x, y); //Explicit call to the super class constructor is mandatory
|
||||
}
|
||||
|
||||
//Overwrite
|
||||
dist() {
|
||||
var d = super.dist();
|
||||
return Math.sqrt(d * d + this.z * this.z);
|
||||
}
|
||||
}
|
||||
|
||||
//Modules, "." can be used as separator for sub modules
|
||||
module Geometry {
|
||||
export class Square {
|
||||
constructor(public sideLength: number = 0) {
|
||||
}
|
||||
area() {
|
||||
return Math.pow(this.sideLength, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var s1 = new Geometry.Square(5);
|
||||
|
||||
//..Local alias for referencing a module
|
||||
import G = Geometry;
|
||||
|
||||
var s2 = new G.Square(10);
|
||||
|
||||
//Generics
|
||||
//..Classes
|
||||
class Tuple<T1, T2> {
|
||||
constructor(public item1: T1, public item2: T2) {
|
||||
}
|
||||
}
|
||||
|
||||
//..Interfaces
|
||||
interface Pair<T> {
|
||||
item1: T;
|
||||
item2: T;
|
||||
}
|
||||
|
||||
//..And functions
|
||||
var pairToTuple = function<T>(p: Pair<T>) {
|
||||
return new Tuple(p.item1, p.item2);
|
||||
};
|
||||
|
||||
var tuple = pairToTuple({ item1:"hello", item2:"world"});
|
||||
|
||||
//Including references to a definition file:
|
||||
/// <reference path="jquery.d.ts" />
|
||||
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
* [TypeScript Official website] (http://www.typescriptlang.org/)
|
||||
* [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238)
|
||||
* [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
|
||||
* [Source Code on GitHub] (https://github.com/Microsoft/TypeScript)
|
||||
* [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
|
Loading…
Reference in New Issue
Block a user