为什么当我尝试定义对象方法时:
export class Helper {
function add(x: number, y: number): number {
return x + y;
}
}
我收到以下错误:
Unexpected token. A constructor, method, accessor, or property was expected.
我在此网站上关注了示例:https://www.typescriptlang.org/docs/handbook/functions.html
但是,当我删除function
关键字时,它会起作用,但这与官方来源相矛盾。
答案 0 :(得分:3)
你不应该在课堂内使用函数!改变它:
import android.app.Service;
import android.content.Intent;
import android.media.MediaRouter;
import android.media.session.MediaSession;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.media.VolumeProviderCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class HookButtonService extends Service{
public static final String SESSION_TAG = "SampleApp";
private MediaSessionCompat mMediaSession;
private VolumeProviderCompat myVolumeProvider;
public class ServiceBinder extends Binder {
public HookButtonService getService() {
return HookButtonService.this;
}
}
private Binder mBinder = new ServiceBinder();
private MediaSessionCompat.Callback mMediaSessionCallback = new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("SampleApp","Media button received");
if(!MyApplication.isActivityVisible()) {
Intent dialogIntent = new Intent(getApplicationContext(), MainActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
return true;
}
};
public HookButtonService() {
}
public MediaSessionCompat.Token getMediaSessionToken() {
return mMediaSession.getSessionToken();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
mMediaSession = new MediaSessionCompat(this, SESSION_TAG);
mMediaSession.setCallback(mMediaSessionCallback);
myVolumeProvider = new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_RELATIVE, 100, 50) {
@Override
public void onAdjustVolume(int direction) {
Log.d("SampleApp","Volume change received: "+direction);
}
};
mMediaSession.setActive(true);
mMediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
mMediaSession.setPlaybackToRemote(myVolumeProvider);
}
@Override
public void onDestroy() {
super.onDestroy();
mMediaSession.release();
}
}
Typescript不允许函数作为类的成员。所以,把它改成一个方法!
正如 mattjes 所说,你可以使方法也是静态的......
export class Helper {
add(x: number, y: number): number {
return x + y;
}
}