npm install -g typescript
TypeScript varsayılan olarak ES3'e göre kodu çevirir.
Eğer daha yüksek bir sürüm hedefliyorsak tsc --target es2015 hello.ts
komutunu kullanabiliriz.
- Detaylı bilgi: target
Güncel tarayıcıların büyük bir çoğunluğu ES6'yı desteklediği için varsayılan hedef bu sürüme yükseltilebilir.
- Detaylı bilgi: ES6 tarayıcı uyumu
Değişkenlerin türlerininin belirtilmesi
function greet(person: string, date: Date) {
console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
Tüm türler: string
, number
, boolean
, number[]
, string[]
, any
Değişkenleri tanımlarken değerini verebiliriz.
let myName: string = "Alice";
Bir fonksiyonda return edilen değerin türünü belirtebiliriz.
function getFavoriteNumber(): number {
return 26;
}
Opsiyonel bir parametre var ise bunu ?
ile belirtebiliriz.
function printName(obj: { first: string; last?: string }) {
// ...
}
// Both OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
Değişkenlere birden çok tür atanabilir.
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId({ myID: 22342 });
Bu şekilde birden çok tür atanan değişkenlerde işlem yaparken typeof
ile tip kontrolü yapmalıyız.
function printId(id: number | string) {
if (typeof id === "string") {
// In this branch, id is of type 'string'
console.log(id.toUpperCase());
} else {
// Here, id is of type 'number'
console.log(id);
}
}
type Point = {
x: number;
y: number;
};
// Exactly the same as the earlier example
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
type ID = number | string;
type
yerine interface
te kullanılabilir (Tamamen aynı şey değildir fakat büyük ölçüde benzerdir):
interface Point {
x: number;
y: number;
}
- Detaylı bilgi: type vs interface
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre"); // Hata
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}
interface Options {
width: number;
}
function configure(x: Options | "auto") {
// ...
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // Hata
interface Shape {
kind: "circle" | "square";
radius?: number;
sideLength?: number;
}
function handleShape(shape: Shape) {
// ...
}
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function greet(person: { name: string; age: number }) {
return "Hello " + person.name;
}
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
return "Hello " + person.name;
}