Skip to content
Typescript to PHP Transpiler.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
demo
src fix: array.prototype.indexOf returns false (#41) May 22, 2019
test fix: array.prototype.indexOf returns false (#41) May 22, 2019
types chore: separate d file May 9, 2019
.editorconfig init Oct 25, 2018
.gitignore chore: add doc generator and github pages Apr 17, 2019
.npmignore chore: add doc generator and github pages Apr 17, 2019
.travis.yml add commit lint Apr 18, 2019
CHANGELOG.md
CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md Mar 15, 2019
LICENSE Create LICENSE Mar 9, 2019
README.md chore: fix reset May 22, 2019
config.example.js refactor: console.log => echo, suport multi arguments Apr 22, 2019
package-lock.json 0.9.4 May 22, 2019
package.json 0.9.4 May 22, 2019
tsconfig.json chore: add changelog config Apr 29, 2019
typescript.d.ts fix: remove useless require #8 Apr 18, 2019

README.md

ts2php

under development

TypeScript 转 PHP

Language Build Status npm package npm downloads

Usage

compiler

import {compile} from 'ts2php';

const result = compile(filePath, options);

runtime

部分功能依赖一个 PHP 的类库,需要在 PHP 工程中引入

require_once("/path/to/ts2php/dist/runtime/Ts2Php_Helper.php");

CLI

简单使用:

$ npm i -g ts2php
$ ts2php ./a.ts                   # 编译输出到 stdout

使用配置并输出到文件:

$ cat config.js
module.exports = {
  emitHeader: false
};
$ ts2php -c config.js src/ -o output/

更多选项:

$ ts2php --show-diagnostics       # 输出诊断信息
$ ts2php --emit-header            # 输出头部信息
$ ts2php -h                       # 更多功能请查看帮助

Features

Javascript Syntax

for/for of/for in

let b = 1;
for (let i = 0; i < 10; i++) {
    b += 10;
}

const a = [1, 2, 3];
for (const iterator of a) {
    console.log(iterator);
}

const d = {a: 1, b: 2};
for (const iterator in d) {
    console.log(iterator);
}

output

$b = 1;
for ($i = 0; $i < 10; $i++) {
    $b += 10;
}
$a = array(1, 2, 3);
foreach ($a as $iterator) {
    echo $iterator;
}
$d = array( "a" => 1, "b" => 2 );
foreach ($d as $iterator) {
    echo $iterator;
}

if/else if/else

const a = true;

if (!a) {
    const b = 456;
    const c = 123;
}
else {
    const d = 789;
}

output

$a = true;
if (!$a) {
    $b = 456;
    $c = 123;
}
else {
    $d = 789;
}

swtich

let b = 2;
let c = 1;
switch (b) {
    case 1:
        c = 2;
        break;
    case 2:
        c = 3;
        break;
    default:
        c = 4;
}

output

$b = 2;
$c = 1;
switch ($b) {
    case 1:
        $c = 2;
        break;
    case 2:
        $c = 3;
        break;
    default:
        $c = 4;
}

while/do while

const a = true;
let b;
while(!a) {
    b = 2;
}
do {
    b++;
} while(!a);

output

$a = true;
$b;
while (!$a) {
    $b = 2;
}
do {
    $b++;
} while (!$a);

Class

import {Base} from '../some-utils';

class Article extends Base {

    public title: string;
    id: number;

    private _x: number;

    static published = [];

    constructor(options: {title: string}) {
        super(options);
        this.title = options.title;
        this.publish(1);
    }

    private publish(id) {
        Article.published.push(id);
        super.dispose();
    }
}

const a = new Article({title: 'a'});
const b = a.base;
a.dispose();

output

namespace test\case_Class;
require_once(realpath(dirname(__FILE__) . '/' . "../some-utils.php"));
use \Base;
class Article extends Base {
    public $title;
    public $id;
    public $foo;
    private $_x;
    public static $published = array();
    function __construct($options) {
        parent::__construct($options);
        $this->title = $options["title"];
        $this->publish(1);
    }
    private function publish($id) {
        array_push(Article::$published, $id);
        parent::dispose();
    }
}
$a = new Article(array( "title" => "a" ));
$b = $a->base;
$a->dispose();

typeof

由于 php 中没有 undefined 关键字,故不支持返回 undefined

const d = typeof c === 'string';

output

$d = \Ts2Php_Helper::typeof($c) === "string";

delete

const e = {a: 1, b: 2};
delete e.a;

output

$e = array( "a" => 1, "b" => 2 );
unset($e["a"]);

destructuring

const tplData: {a: number, difftime?: number, c?: 1} = {a: 1};

const {
    difftime = 8,
    a,
    c: y = 1
} = tplData;

let a = [1, 2, 3];
const [, e, f] = a;

output

$tplData = array( "a" => 1 );
$difftime = isset($tplData["difftime"]) ? $tplData["difftime"] : 8; $a = $tplData["a"]; $y = isset($tplData["c"]) ? $tplData["c"] : 1;
$a = array(1, 2, 3);
$e = $a[1]; $f = $a[2];

template string

const b = '123';
const c = `0${b}45'6'"789"`;

output

$b = "123";
$c = "0" . $b . "45'6'\"789\"";

object computed property

let a = 'aaa';
let b = 'bbb';
let c = {
    [a + b]: 123,
    [b]: 456
};

output

$a = "aaa";
$b = "bbb";
$c = array(
    ($a . $b) => 123,
    ($b) => 456
);

object shorthand property

let b = 2;
let c = 1;
const a = {
    b,
    c
};

output

$b = 2;
$c = 1;
$a = array(
    "b" => $b,
    "c" => $c
);

object method

const a = {
    b() {
        return "111";
    }
};

output

$a = array(
    "b" => function () {
        return "111";
    }
);

enum

enum aaa {a = 1, b, c}
enum bbb {a, b, c}
enum ccc {
    a = 'a',
    b = 'b',
    c = 'c'
}

const str = '123';
enum ddd {
    a = str.length,
    b = str.length + 1
}
$aaa = array( "a" => 1, "b" => 2, "c" => 3 );
$bbb = array( "a" => 0, "b" => 1, "c" => 2 );
$ccc = array( "a" => "a", "b" => "b", "c" => "c" );
$str = "123";
$ddd = array( "a" => strlen($str), "b" => strlen($str) + 1 );

pass by reference when the arg is an object

function aaa(m: number[]) {
}
function aaa(&$m) {
}

anonymous function inherit variables

let b = 'b';
let f = function () {
    return '123' + b;
}
$b = "b";
$f = function () use(&$b)  {
    return "123" . $b;
};

rest function arguments

function funcA(...args: string[]) {
}
function funcC(a: string, ...args: string[]) {
}

output

function funcA() {
    $args = func_get_args();
}
function funcC() {
    $a = func_get_arg(0); $args = array_slice(func_get_args(), 1);
}

注:箭头函数暂不支持

Core JavaScript API

  • parseInt 只接收一个参数
  • parseFloat
  • encodeURIComponent
  • decodeURIComponent
  • __dirname
  • __filename
  • Date
    • Date.now
    • Date.prototype.getTime
    • Date.prototype.getDate
    • Date.prototype.getDay
    • Date.prototype.getFullYear
    • Date.prototype.getHours
    • Date.prototype.getMinutes
    • Date.prototype.getMonth
    • Date.prototype.getSeconds
    • Date.prototype.setDate
    • Date.prototype.setFullYear
    • Date.prototype.setHours
    • Date.prototype.setMinutes
    • Date.prototype.setMonth
    • Date.prototype.setSeconds
    • Date.prototype.setTime
  • Object
    • Object.assign
    • Object.keys
    • Object.values
    • Object.freeze
  • JSON
    • JSON.stringify 只接收一个参数
    • JSON.parse 只接收一个参数
  • console
    • console.log
    • console.info 转成var_dump
    • console.error
  • String
    • String.prototype.replace
    • String.prototype.trim
    • String.prototype.trimRight
    • String.prototype.trimLeft
    • String.prototype.toUpperCase
    • String.prototype.toLowerCase
    • String.prototype.split
    • String.prototype.indexOf
    • String.prototype.substr
    • String.prototype.substring
    • String.prototype.repeat
    • String.prototype.startsWidth
    • String.prototype.endsWidth
    • String.prototype.includes
    • String.prototype.padStart
  • Array
    • Array.isArray
    • Array.prototype.length
    • Array.prototype.filter 回调函数只接收第一个参数
    • Array.prototype.push
    • Array.prototype.pop
    • Array.prototype.shift
    • Array.prototype.unshift
    • Array.prototype.concat
    • Array.prototype.reverse
    • Array.prototype.splice
    • Array.prototype.reverse
    • Array.prototype.map 回调函数只接收第一个参数
    • Array.prototype.forEach 回调函数只接收第一个参数
    • Array.prototype.indexOf
    • Array.prototype.join
  • Number
    • Number.isInterger
    • Number.prototype.toFixed
  • Math
    • Math.abs
    • Math.acos
    • Math.acosh
    • Math.asin
    • Math.asinh
    • Math.atan
    • Math.atanh
    • Math.atan2
    • Math.cbrt
    • Math.ceil
    • Math.clz32
    • Math.cos
    • Math.cosh
    • Math.exp
    • Math.expm1
    • Math.floor
    • Math.hypot
    • Math.log
    • Math.log1p
    • Math.log10
    • Math.max
    • Math.min
    • Math.pow
    • Math.random
    • Math.round
    • Math.sin
    • Math.sinh
    • Math.sqrt
    • Math.tan
    • Math.tanh

Thanks to

Based on Typescript compiler

You can’t perform that action at this time.