This guide presents a syntax comparison between PHP (7 minimum) and TypeScript. This is an extension of From PHP to JavaScript ES6 guide, that you should read first.
You'll find other guides and a general explanation here.
Why TypeScript ? As a PHP developer working with frameworks like Symfony or Zend, you'll love it, and we explain why here. Static data types is also the big new feature of PHP 7.
Simple data types
PHP has always allowed explicit types, but just for conversion. TypeScript enforces types, you cannot change them afterwards. Integers and decimal numbers share the same type in JavaScript.
/* PHP */ $userMan = (bool) true; $userAge = (int) 81; $userAverage = (float) 10.5; $userName = (string) 'Henri Bergson'; $userName = 10; // OK
/* TypeScript */ let userMan: boolean = true; let userAge: number = 81; let userAverage: number = 10.5; let userName: string = "Henri Bergson"; userName = 10; // Error
Lists data types
In PHP, you just tell something is an array. In TypeScript, you specify an array of what, as arrays are only for homogeneous data in JavaScript.
/* PHP */ $books = (array) ['Book 1', 'Book 2']; $list = (array) ['a', 'b', 10]; // OK
/* TypeScript */ let books: string[] = ["Book 1", "Book 2"]; let list: string[] = ['a', 'b', 10]; // Error
As a JavaScript object is like a literal instance, you can use TypeScript interfaces as its type.
/* TypeScript */
interface User {
age: number;
name: { first: string, last: string };
}
let user: User = {
age: 81,
name: { first: "Henri", last: "Bergson" }
};
Types in functions
PHP always allowed to check classe instances for parameters.
/* PHP */ function myMethod(User $someUser) {}
/* TypeScript */ function myMethod(someUser: User) {}
PHP 7 introduced checking for simple data types for parameters, also with return type. But be aware they are enforced only on demand.
/* PHP 7 - strict */ declare(strict_types=1); function myMethod(string $data): int { return 10; } myMethod(20); // Error /* PHP 7 - normal */ function myMethod(string $data): int { $data; // '20' return 10; } myMethod(20); // OK
/* TypeScript */ function myMethod(data: string): int { return 10; } myMethod(20); // Error
PHP 7.1 will allow to specify if a function has no return.
/* PHP 7.1 */ function myMethod(): void {}
/* TypeScript */ function myMethod(): void {}
Classes
TypeScript adds pre-declared properties and visiblity modifiers, not yet available in standard JavaScript.
/* PHP */ class User { public $firstName; protected $lastName; private $age; public function __construct() {} }
/* TypeScript */ class User { public firstName: string; protected lastName: string; private age: int; public constructor() {} }
TypeScript also adds abstract classes and interfaces.
/* PHP */ interface Movable { public move(); } class Vehicle implements Movable { public move() {} } abstract class Test {}
/* TypeScript */ interface Movable { public move(): void; } class Vehicle implements Movable { public move(): void {} } abstract class Test {}