sindresorhus / got

🌐 Human-friendly and powerful HTTP request library for Node.js
MIT License
14.27k stars 935 forks source link

.get<Type>() returns string #1848

Closed bato3 closed 3 years ago

bato3 commented 3 years ago

Describe the bug

typof body is string instead Object

const {body} = await client().get<User>(`users/${name}`);

TS hints shows that it should be User, during run app it shows string

Actual behavior

typof body == 'string'

TS error when I try JSON.parse(body):

Argument of type 'User' is not assignable to parameter of type 'string'.ts(2345)

Expected behavior

typof body == 'User'

Code to reproduce

import got, {Got} from 'got';
const pjson = require('../package.json');
let clientInstance: Got= got.extend({
            prefixUrl: process.env.OPENFIRE_REST_BASE_URL,
            headers: {
                'Authorization' : process.env.OPENFIRE_REST_SECRET_KEY ,
                'Content-Type' : 'application/json',
                accept: 'application/json',
                'user-agent': process.env.OPENFIRE_REST_USERAGENT || `${pjson.name}/${pjson.version}`
            }
        });

export async function user(name: string): Promise<User> {
    const resp = await clientInstance.get<User>(`users/${name}`);

    console.log(resp.headers, typeof resp.body);
    JSON.parse(resp.body)
    return resp.body
}

user('admin').catch(ex => console.log(ex)).then(d => {
    //@ts-expect-error
    console.log(d, typeof d, JSON.parse(d))
})

Checklist

szmarczak commented 3 years ago

https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#responsetype

szmarczak commented 3 years ago

Or use promise.json<User>().