如您所知,从 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) 免责声明:过度简化的功能如下,我知道它们没用
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>不是有效的打字稿.
如何根据泛型获得具有不同返回类型的函数的返回类型?
这是我的第一次尝试:( 游乐场链接)
/** 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)