相关疑难解决方法(0)

如何在 vue 3 中从 `defineComponent()` 中键入 vue 实例?

如您所知,从 Vue 3 开始,组件可以用 TypeScript 编写:

/// modal.vue

<template>
  <div class="modal"></div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Modal",
  props: {
    foo: String,
    bar: String
  },
  mounted() {
    this.$props.foo // how to type `this` out of this context?
  }
});
</script>
Run Code Online (Sandbox Code Playgroud)

我的问题是如何从defineComponent函数中键入 vue 实例?

/// another ts file.
let modal:???; // what the `???` should be?

modal.$props.foo // infer `$props.foo` correctly
Run Code Online (Sandbox Code Playgroud)

typescript vue.js

5
推荐指数
2
解决办法
2773
查看次数

获取使用泛型的函数的返回类型

免责声明:过度简化的功能如下,我知道它们没用

function thinger<T>(thing: T): T {
    return thing;
}

const thing = thinger({ a: "lol" });

thing.a;
Run Code Online (Sandbox Code Playgroud)

上面的代码转换得很好.但我需要将结果thinger<T>放入一个对象中.

interface ThingHolder {
    thing: ReturnType<typeof thinger>;
}

const myThingHolder: ThingHolder = {
    thing: thinger({ a: "lol" }),
};
Run Code Online (Sandbox Code Playgroud)

但是我丢失了我的类型信息,所以myThingHolder.thing.a不起作用

类型"{}"上不存在属性"a"

所以我尝试了以下内容

interface ThingHolder<T> {
    thing: ReturnType<typeof thinger<T>>;
}

const myThingHolder: ThingHolder<{ a: string }> = {
    thing: thinger({ a: "lol" }),
};
Run Code Online (Sandbox Code Playgroud)

但是typeof thinger<T>不是有效的打字稿.

如何根据泛型获得具有不同返回类型的函数的返回类型?

generics typescript typescript-generics

4
推荐指数
1
解决办法
827
查看次数

如何测试两种类型是否完全相同

这是我的第一次尝试:( 游乐场链接)

/** Trigger a compiler error when a value is _not_ an exact type. */
declare const exactType: <T, U extends T>(
    draft?: U,
    expected?: T
) => T extends U ? T : 1 & 0

declare let a: any[]
declare let b: [number][]

// $ExpectError
exactType(a, b)
Run Code Online (Sandbox Code Playgroud)

相关:https://github.com/gcanti/typelevel-ts/issues/39

typescript

1
推荐指数
4
解决办法
190
查看次数