在文件中创建计算类型的导出

Tho*_*ggi 8 typescript

我想知道是否有可能给一个具有导出类型的文件,这些类型是否可以从泛型中提取计算类型?

function example() {
  return {
    foo: 'hi',
    bar: true,
    baz: 1
  };
}

export type Signature = ReturnType<typeof example>;
Run Code Online (Sandbox Code Playgroud)

对此:

export type Signature = {
    foo: string;
    bar: boolean;
    baz: number;
}
Run Code Online (Sandbox Code Playgroud)

我不相信tsccli会这样做,我不确定这个过程会被称为什么。

可以tsc创建这个导出吗?

有没有第三方工具可以做到这一点?

我知道如何做到这一点的唯一方法是将鼠标悬停在 VSCode 中的变量上并复制计算类型,并且只有在它很短并且不会减弱时才有效......

我发现了其他一些对类似请求的引用:

vik*_*ike 6

调查这个问题,在不复制 VSCode 的情况下hover.ts,我发现这个问题的答案是:

从中提取悬停“quickinfo” tsserver

您需要将文件中的行和字符偏移量传达给服务器。每个人都应该能够使用抽象语法树(AST).ts的这一点。我用 bash 写了一个客户端。下面附上,它支持从列计算字符偏移量(如 VSCode 状态栏中所示)。来自源代码运行的日志和“签名”一词上的文档位置紧随其后,结尾非常接近您想要的提取。

$ (prepared=('open -s #.ts -i file' 'quickinfo -s #.ts -i file -n 9 -i line -n 20 -i _column_')&&. $(which tsssh))
ts < open -s #.ts -i file
{"seq": 1, "type": "request", "command": "open", "arguments": {"file": "#.ts"}}
ts < quickinfo -s #.ts -i file -n 9 -i line -n 20 -i _column_
{"seq": 1, "type": "request", "command": "quickinfo", "arguments": {"file": "#.ts", "line": 9, "offset": 19}}
event #0
event: typingsInstallerPid
body: {"pid": 65341}
response #0 (1)
command: quickinfo
body: {"kind": "type", "kindModifiers": "export", "start": {"line": 9, "offset": 13}, "end": {"line": 9, "offset": 22}, "displayString": "type Signature = {\n    foo: string;\n    bar: boolean;\n    baz: number;\n}", "documentation": "", "tags": []}
displayString: type Signature = {
    foo: string;
    bar: boolean;
    baz: number;
}
Run Code Online (Sandbox Code Playgroud)
  • https://github.com/Microsoft/TypeScript/wiki/Standalone-Server-%28tsserver%29 的快速而肮脏的客户端.
  • 严重依赖先决条件http://kmkeen.com/jshon/,以及兼容的 bash 和 gawk,而 tput 和 tee 可能会被删除,我猜..
  • 在 macOS 10.13.6 版本5.0.16 上开发,bash -O cmdhist -O lithist带有 macports,以及其他各种商店
  • 注意:您需要通过发送空命令行来手动轮询事件/响应。用 kill -sigint 退出,通常是 ctrl+C..
  • 在本地 repo 中运行,例如tsserver=./node_modules/typescript/bin/tsserver tsssh..
  • 禁用历史记录histfile= path/to/tsssh。多个“准备”可以指定为(prepared=("first" ... "last")&&. path/to/tsssh)
#!/usr/bin/env bash
( # Quick and dirty client for https://github.com/Microsoft/TypeScript/wiki/Standalone-Server-%28tsserver%29..
  # Relies heavily on prerequisite http://kmkeen.com/jshon/, and compatible bash and gawk, while tput and tee could be cut out I guess..
  # Developed on macOS 10.13.6 in version 5.0.16 `bash -O cmdhist -O lithist` with macports, and various other shopt..
  # NB: You need to poll event/response manually by sending empty commandlines. Exit with kill -sigint , typically ctrl+C..
  # Run in local repo like `tsserver=./node_modules/typescript/bin/tsserver tsssh`..
  # Disable history with `histfile='' path/to/tsssh`. Multiple "prepared" can be specified as `(prepared=("first" ... "last")&&. path/to/tsssh)`
  # Copyright 2020 Viktor Bergquist (vike2000@gmail.com), license https://creativecommons.org/licenses/by-sa/4.0/
  HISTFILE=${histfile-.tsssh_history} &&
  { ((\!-( x = xtrace )))||set -x ;} && ((!errexit))||set -e &&
  state()(set +x;tput setaf $1;echo "${*:2}";tput sgr0;((\!-x))||set -x) >&2 && trap 'state 1 $?: "$BASH_COMMAND"' err &&
  [[ ! $HISTFILE ]]||{ h=$HISTSIZE&&HISTSIZE=1&&set -o history&&HISTSIZE=$h&&history -s ''&&{ history -r "$HISTFILE"||:;};}&&
  coproc ts (${tsserver:-tsserver}) &&set -o pipefail&&command sleep 1 &&
  show(){ set +x; f=$1&&shift && i=$(cat) && declare -n n&&for n;do
      n=$(((\!-x))||set -x; jshon <<<"$i" -e "${!n}" $f);((e=$?)) || echo "${!n}: $n"; done; ((\!-x))||set -x; return $e;} &&
  extract(){ show "$@";} >/dev/null &&
  compact()( "$@"|gawk -vORS= '{sub("^\\s+",!m[0]?"":" ")}1;{match($0,",$",m)}END{printf"\n"}') &&
  function check(){ while {
        read -rt.1 -d$'\r' h&&[[ $h =~ Content-Length:\ ([0-9]+) ]]&&read -r$t -N3&&read -r$t -N$((${BASH_REMATCH[1]}-1)) a;} <&${ts[0]};do
      #set +x;echo 'ts > '"$a";((\!-x))||set -x
                <<<"$a" extract -u type seq &&case $type in
      (   event)state 2 $type \#$seq
                <<<"$a" show -u event ;;&
      (response)<<<"$a" extract -u success request_seq&&case $success in
        ( false)state 1 $type \#$seq "($request_seq)"
                <<<"$a" show -u command message ;;
        (  true)state 2 $type \#$seq "($request_seq)"
                <<<"$a" show -u command message metadata 2>/dev/null ;;
        (     *)state 1 "unknown success: $success" ;esac ;&
      (   event)<<<"$a" compact show '' body ;! [[ $type = response && $success = true ]]||case $command in
        (     *)<<<"$a" extract '' body ;;&
        ( quickinfo) <<< "$body" show -u displayString ;esac ;;
      (       *)state 1 "unknown type: $type" ;esac ;done;} &&
  seq=0 && for p in ${!prepared[@]} -1;do for fd in <(echo "${prepared[p]}") 0;do fd="${fd##*/}"; (((p<0)!=(0<fd)))||continue
      while check <&-; set +x; read -p 'ts < ' -era Q; do
        ((\!${#Q[*]}))&&{ tput -S<<<$'cuu1\nel'
          ((\!-x))||set -x;} ||
        { ((\!-x))||set -x
          history -s "${Q[*]}"&&{ [[ ! $HISTFILE ]]||{ [[ ! -a $HISTFILE ]]&&history -w "$HISTFILE"||history -a "$HISTFILE";};} &&
          d=$(compact jshon <<<{} -n$((++seq)) -i seq -s request -i type -s "$Q" -i command -n {} "${Q[@]:1}" -i arguments)
          A=$(compact jshon <<<{} "${Q[@]:1}")
          ! <<<"$A" extract -u file line _column_ 2>/dev/null ||
          { o=$(gawk -vT="${tabs:-4}" -vC="$_column_" FNR=="$line"'{
              t=-1;for(o=0;o<=length();o++){t++;if("\t"==substr($0,o,1)){t+=T-1;t-=t%T}if(t>=C)break}print o-1
              }' "$file") &&
            d=$(<<<"$d" compact jshon -e arguments -d _column_ -n "$o" -i offset -p);}
          tee   <<<"$d" /dev/stderr >&${ts[1]};}
        done<&$fd;done;done;set +x;echo bye) #ts < eg: reload -s index.ts -i file ^M quickinfo -s index.ts -i file -n 4 -i line -n 7 -i _column_
Run Code Online (Sandbox Code Playgroud)

有了你所有问题的良好参考,你肯定知道你提到的一些“线索”可以通过 "compilerOptions":{"noErrorTruncation":true}tsconfig.json:) 中

在这些参考文献的末尾,我可以补充说还有一个 交互式诊断 PR 31384(草案)期待:)

目前,我将在相关问答中研究有趣的实用程序类型如何查看 Typescript 类型的完整扩展合同?