Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

参数是变量,ts的返回值怎么写

export function transDictToArray(
  dict: Record<string, unknown>,
  keyLabel = "value",
  valueLabel = "label"
): Array<{
  [keyLabel]: string;
  [valueLabel]: string;
}> {
  const arr = [];
  for (const key in dict) {
    if (Object.prototype.hasOwnProperty.call(dict, key)) {
      arr.push({
        [keyLabel]: key,
        [valueLabel]: dict[key],
      });
    }
  }
  return arr;
}

报错:类型文本中的计算属性名称必须引用类型为文本类型或 "unique symbol" 类型的表达式。ts(1170)

ts不能用变量作为返回值吗


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

那就要用到类型世界里的参数----泛型了啦。

不考虑默认值问题会比较简单: TS Playground

function transDictToArray<TK extends string, TV extends string>(
  dict: Record<string, unknown>,
  keyLabel: TK,
  valueLabel : TV
): Record<TK|TV, string>[] {
  const arr: Record<TK|TV, string>[]  = [];
  for (const key in dict) {
    if (Object.prototype.hasOwnProperty.call(dict, key)) {
      const item = {
        [keyLabel]: key,
        [valueLabel]: dict[key] as string,
      } as  Record<TK|TV, string>;
      arr.push(item);
    }
  }
  return arr;
}

const arr = transDictToArray({a: 1, b: 2}, 'kkk', 'vvv');
let kkk = arr[0].kkk;

考虑默认参数的话,只能用重载实现了:

TS Playground

function transDictToArray<TK extends string, TV extends string>(
  dict: Record<string, unknown>,
  keyLabel: TK,
  valueLabel : TV
): Record<TK|TV, string>[];

function transDictToArray<TK extends string>(
  dict: Record<string, unknown>,
  keyLabel: TK,
  valueLabel?:'value'
): Record<TK|'value', string>[];

function transDictToArray(
  dict: Record<string, unknown>,
  keyLabel?: 'label',
  valueLabel?:'value'
): Record<'label' |'value', string>[];


function transDictToArray(
  dict: Record<string, unknown>,
  keyLabel: string = 'label',
  valueLabel : string = 'value'
): Record<string, string>[] {
  const arr: Record<string, string>[]  = [];
  for (const key in dict) {
    if (Object.prototype.hasOwnProperty.call(dict, key)) {
      arr.push({
        [keyLabel]: key,
        [valueLabel]: dict[key] as string,
      });
    }
  }
  return arr;
}

transDictToArray({a: 1, b: 2}, 'kkk', 'vvv')[0].kkk;
transDictToArray({a: 1, b: 2}, 'kkk')[0].value;
transDictToArray({a: 1, b: 2})[0].label;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...