Skip to content

Go Decorators API

Go strings 包 —— 用于操作 UTF-8 字符串的函数。

1 class · 4 methods

strings

4 methods

strings 包实现了操作 UTF-8 编码字符串的简单函数。

@ClassDecorator(target: Function)

如果 substr 包含在 s 中则返回 true。

Parameters

NameTypeDescription
targetFunction要搜索的字符串。

Returns

Function | void

Example

typescript
function logged<T extends { new (...a: any[]): {} }>(Base: T) {
  return class extends Base {
    constructor(...a: any[]) { super(...a); console.log('constructed'); }
  };
}
@logged
class Foo {}
new Foo();  // logs 'constructed'
@MethodDecorator(target, key, descriptor)

如果 s 以 prefix 开头则返回 true。

Parameters

NameTypeDescription
targetobject要检查的字符串。
prefixstring | symbol要测试的前缀。
descriptorPropertyDescriptorMethod descriptor.

Returns

PropertyDescriptor | void

Example

typescript
function log(target: any, key: string, desc: PropertyDescriptor) {
  const orig = desc.value;
  desc.value = function (...a: any[]) {
    console.log('call', key, a);
    return orig.apply(this, a);
  };
}
class Calc {
  @log
  add(a: number, b: number) { return a + b; }
}
@PropertyDecorator(target, key)

如果 s 以 suffix 结尾则返回 true。

Parameters

NameTypeDescription
targetobject要检查的字符串。
suffixstring | symbol要测试的后缀。

Returns

void

Example

typescript
const meta = new WeakMap();
function Column(target: any, key: string) {
  meta.set(target, [...(meta.get(target) ?? []), key]);
}
class User {
  @Column name!: string;
  @Column email!: string;
}
@ParameterDecorator(target, key, paramIndex)

返回 substr 在 s 中首次出现的索引,不存在则返回 -1。

Parameters

NameTypeDescription
targetobject要搜索的字符串。
substrstring | symbol | undefined要查找的子字符串。
paramIndexnumberIndex of the parameter.

Returns

void

Example

typescript
function Req(target: any, key: string, idx: number) {
  console.log(`@Req on ${key}[${idx}]`);
}
class Ctrl {
  handler(@Req body: unknown) {}
}